Hash table array

02/03/2013 02:08


#Declare empty array with type to enable adding hashes
[array]$arrayOfhashes = @();
   
Write-Host ""
$newItem = @{MyNumber1 = 7800; MyNumber2 = 2}
$newItem

#add first item
$arrayOfhashes += $newItem

Write-Host ""
$newItem = @{MyNumber1 = 780330; MyNumber2 = 45}
$newItem

#add next item
$arrayOfhashes += $newItem
Write-Host ""

Write-Host "Array of hashes after adding"
Write-Host "============================"
$arrayOfhashes

#Find item in hash array
Write-Host ""
Write-Host "Find item in has array"
Write-Host "======================"
 $found = $null        
 foreach($item in $arrayOfhashes)
 {
  if($item.MyNumber2 -eq 45)
  {
   $found = $item
   break;
  }
 }
 if($found -eq $null)
 {
  Write-Host "NOt found"
 }
 else
 {
  Write-Host "Item with MyNumber2 = 45 was found."
  $item
 }

 

Output:

Name Value

---- -----

MyNumber1 7800

MyNumber2 2

MyNumber1 780330

MyNumber2 45

Array of hashes after adding

============================

MyNumber1 7800

MyNumber2 2

MyNumber1 780330

MyNumber2 45

Find item in has array

======================

Item with MyNumber2 = 45 was found.

MyNumber1 780330

MyNumber2 45