Introduction

Today we’re going to be creating hash tables in Windows Powershell. A hash table is basically an associative array that uses key value pairs to store information. Many data stores use the key value notation, so learning how to create and manipulate hash tables is important.

Creating And Manipulating Hash Tables

Creating a hash table is not a complicated task. It’s basically the same as creating a regular array, except there are a few syntax differences. Let’s take a look at an example of a hash table or an associative array:

Let’s dissect the line above. We begin by declaring the name of our hash table as $hashTable. The dollar sign denotes that this is a variable. We specify that it’s a hash table by using @{}.
Notice how the key values aren’t in quotes. Only string values need to be in quotes within a hash table. You may also notice that we have three values in the value portion of our last entry, this automatically creates an array so the value of our key favNumbers is the array [5, 7, 9].

The following code is another way to add items to a hash table:

This method of assigning data to your hash table uses the string within the brackets as the key, the value in this case is 22. Believe it or not, there’s another way to add key value pairs to hash tables, and in my opinion it’s the quickest and easiest:

You can also call the value of those pairs utilizing the same syntax like so:

This script will print the values of those keys out into the PowerShell console. You can view all the key value pairs in your hash table by writing the following:

You’ll notice that the hash table wasn’t kept in the same order you declared all the values in, to do this you can use the Ordered type cast. Review the following for usage of Ordered:

Congratulations! Now you know how to create and manipulate hash tables in PowerShell. This will certainly come in handy at some point as a system administrator. To learn more about hash tables in PowerShell, visit Microsoft’s Tech Net technet.microsoft.com.