Looping Through a PowerShell Hashtable Foreach Like an Array

Adam Bertram

Adam Bertram

Read more posts by this author.

Coming directly from scripting on the web with PHP I thought a PowerShell hashtable foreach was simply another array; an associate array. I mean, it’s just an array just with some key/value pairs instead of single elements, right? No.

Imagine my surprise when I did this and didn’t get anything.

$hash_table = @{'key1' = 'value1';'key2' = 'value2';'key3' = 'value3'}
$hash_table | Foreach-Object { $_.Value }
A PowerShell hash table can not iterate a loop on it's own
A PowerShell hash table can not iterate a loop on it’s own

What I didn’t realize was that a hashtable is actually a single PowerShell object. It’s not an actual collection like I’m used to. There’s a method on each hashtable object called GetEnumerator().

To process each key/value pair in a hashtable the GetEnumerator() method must be called on the hashtable to break it apart. This method essentially tells the hashtable object to send each key/value pair to the pipeline individually. Now try this:

$hash_table = @{'key1' = 'value1';'key2' = 'value2';'key3' = 'value3'}
$hash_table.GetEnumerator() | % { $_.Value }
Using the GetEnumerator() method on a hashtable
Using the GetEnumerator() method on a hashtable

Much better, huh? Lesson learned.

Subscribe to Adam the Automator

Get the latest posts delivered right to your inbox

Looks like you're offline!