[Powershell-Basics] – Looping through hash table


This post will show how to loop through a hash table in PowerShell.

Let’s say for example we have a hashTable object in PowerShell as shown below:

$SampleTable = @{}   # Syntax for creating hashtable --> @{}
$SampleTable."Name" = "Amogh"
$SampleTable."City" = "Hyderabad"
$SampleTable."Country" = "India"

For looping through the hashtable, we can use the method GetEnumerator() method of the Hashtable class. This provides an enumerator that can be used in the Foreach loop. And we can use the Key and Value property of the hash table entry.

Foreach($Entry in $SampleTable.GetEnumerator())
        Write-Output "$Entry.Key ------ $Entry.Value"

The output of the above snippet will be as follows:

Name ------ Amogh
City ------ Hyderabad
Country ------ India

Hope this helps!

This entry was posted in PowerShell and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *