PowerShell: How to Iterate Over a Hash Table


You can use the following basic syntax to iterate over a hash table in PowerShell:

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

This particular example iterates over each element of the hash table named $my_hashtable and outputs the key and value.

The following example shows how to use this syntax in practice.

Example: How to Iterate Over a Hash Table in PowerShell

Suppose we create the following hash table in PowerShell that contains keys that represent employee ID numbers and values that represent the employee names:

$employees = @{
  A0001 = 'Andy';
  A0002 = 'Bob';
  A0003 = 'Chad';
  A0004 = 'Derrick';
  A0005 = 'Erin';
  A0006 = 'Frank';
  A0007 = 'Greg';
}

The following screenshot shows how to use this syntax in practice:

Suppose we would like to iterate over this hash table and output each key and value pair.

We can use the following syntax to do so:

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

The following screenshot shows how to use this syntax in practice:

PowerShell iterate over hash table

Notice that we are able to iterate over each element in the hash table and output the key value pairs in the following format: key: value.

Note that you could also output the keys and values in a different format if you would like.

For example, you could separate the keys and values using a comma instead:

foreach ($h in $employees.GetEnumerator()) {
    Write-Host "key = $($h.Name), value = $($h.Value)"
}

The following screenshot shows how to use this syntax in practice:

Notice that we are able to iterate over each element in the hash table and output the key and value pairs separated by a comma.

Feel free to use whatever format you would like when iterating over the elements of your hash table.

Note: You can find the complete documentation for the GetEnumerator method in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Check if Hash Table Contains Specific Key
PowerShell: How to Check if File Contains Specific String
PowerShell: How to Replace Special Characters in String

Leave a Reply