Iterate Over A Hashtable in PowerShell

Iterating over an array in PowerShell using a foreach loop is pretty simple. You might think you can do the same thing with a hash table using the same syntax, but if you do you’ll get nothing back.

It is possible to loop over a hash table though, using one of two methods.

First, let’s create a simple hashtable.

$hash = @{
'About Arcane Code' = 'http://arcanecode.me'
'ArcaneCode Blog' = 'https://arcanecode.com'
'ArcaneCode RedGate Articles' = 'http://arcanecode.red'
'ArcaneCode Github Repository' = 'http://arcanerepo.com'
}

In the first method, the one that I prefer, you can use the GetEnumerator method of the hash table object.

foreach ($h in $hash.GetEnumerator() )
{
  Write-Host "$($h.Name) : $($h.Value)"
}

Within the loop, you can use the Name property to get the key part of the hash, and the Value property to retrieve the value. Here is the output:

ArcaneCode Blog : https://arcanecode.com 
ArcaneCode Github Repository : http://arcanerepo.com 
About Arcane Code : http://arcanecode.me 
ArcaneCode RedGate Articles : http://arcanecode.red

In the second method, instead of iterating over the hash table itself, we loop over the Keys of the hash table.

foreach ($h in $hash.Keys) 
{
  Write-Host "$h: $($hash.Item($h))"
}

For each key, we retrieve it’s value from the hash table using the key to indicate the item we want. We could have shortened this slightly, but skipping the Item and just referencing the value by the key, using this syntax:

foreach ($h in $hash.Keys) 
{
  Write-Host "$h: $($hash.$h)"
}

Both of these methods produce the same output as our original version.

ArcaneCode Blog : https://arcanecode.com 
ArcaneCode Github Repository : http://arcanerepo.com 
About Arcane Code : http://arcanecode.me 
ArcaneCode RedGate Articles : http://arcanecode.red

There you go, two simple ways in which you can iterate over a hash table in PowerShell. As I indicated, I prefer GetEnumerator because I have access to both the key and the value in a single variable within my loop. But feel free to use the method that works best for your situation.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s