Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the current hash key in a ForEach-Object loop in powershell

I've got a hash table:

$myHash = @{ 
   "key1" = @{
       "Entry 1" = "one"
       "Entry 2" = "two"
   }
   "key 2" = @{
       "Entry 1" = "three"
       "Entry 2" = "four"
   }
}

I'm doing a loop through to get the objects:

$myHash.keys | ForEach-Object {
    Write-Host $_["Entry 1"]
}

Works fine, but what can I use to figure out which of the keys of $myHash I'm in? $_.Name doesn't return anything. I'm stumped. Help?

like image 499
Matt Simmons Avatar asked Feb 14 '13 17:02

Matt Simmons


2 Answers

I like to use GetEnumerator() when looping a hashtable. It will give you a property value with the object, and a property key with it's key/name. Try:

$myHash.GetEnumerator() | % { 
    Write-Host "Current hashtable is: $($_.key)"
    Write-Host "Value of Entry 1 is: $($_.value["Entry 1"])" 
}
like image 57
Frode F. Avatar answered Nov 08 '22 05:11

Frode F.


You can also do this without a variable

@{
  'foo' = 222
  'bar' = 333
  'baz' = 444
  'qux' = 555
} | % getEnumerator | % {
  $_.key
  $_.value
}
like image 6
Zombo Avatar answered Nov 08 '22 06:11

Zombo