[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!


Your comments or opinions.....

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