PowerShell Hash Tables

A hash table in PowerShell stores data in key and value pairs, similar to a dictionary in the physical world where the word is the key and the description is the value. These pairs are organised based on a hash code of the key, instead of new items being added to the bottom or stored alphabetically. A key must be unique and cannot be null, whilst the value can be null and does not need to be unique.

The example below shows the declaration of a hash table, with four items added to it using the 'Add' method. All of the keys are strings, containing a person's name, whilst all the values are numeric, comprising of an age, corresponding to the name in the key.

$people = @{}

$people.Add("Bob Smith", 30)
$people.Add("George Jones", 21)
$people.Add("Fred Bloggs", 43)
$people.Add("Alan White", 29)

It should be noted that as with other types of variables, the data type can be explicitly stated.

[hashtable] $people = @{}

The declaration and initialisation can be combined into one statement, so the above could be re-written as follows.

$people = @{
    "Bob Smith" = 30;
    "George Jones" = 21;
    "Fred Bloggs" = 43;
    "Alan White" = 29;
}

Regardless of the method used to declare and initialise the hash table, a 'foreach' loop can be used to process its contents. Here, the key and value for each person are incorporated in to a sentence stating a person’s age.

foreach ($person in $people.Keys) 
{
    Write-Host "$person is $($people[$person]) years old."
}

The output in the terminal from the above example is as follows. Notice that the order of the items differs from how they were added to the hash table.

George Jones is 21 years old.
Bob Smith is 30 years old.
Fred Bloggs is 43 years old.
Alan White is 29 years old.

It is also possible to access a single value if the key is known.

Write-Host $people["Bob Smith"]

Similarly, the key can be used to both update and remove a key and value pair using the 'Set_Item' and 'Remove' methods respectively. It should be noted that if an attempt is made to change the value for a key that doesn't exist it has the effect of adding a new key and value pair to the hash table.

$people.Set_Item("Bob Smith", 31)
$people.Remove("Bob Smith")

Finally, it is possible to check if a particular key or value exists in the hash table using the methods 'ContainsKey' and 'ContainsValue'.

# Check if the key exists in the hash table.
if ($people.ContainsKey("Bob Smith"))
{
    Write-Host "The key exists in the hash table."
}
else
{
    Write-Host "The key doesn't exist in the hash table."
}

# Check if the value exists in the hash table.
if ($people.ContainsValue(30))
{
    Write-Host "The value exists in the hash table."
}
else
{
    Write-Host "The value doesn't exist in the hash table."
}