PowerShell : Hash tables

A Hashtable, also known as a dictionary or associative array, is a compact data structure that stores one or more key/value pairs.

When using a Hashtable, you specify an object that is used as a key and the value that you want to be linked to that key.

Generally, we used String or numbers as keys.

Guidelines to create Hashtable.

  • Begin the hash table with an at sign (@).
  • Enclose the hash table in braces ({}).
  • Enter one or more key/value pairs and use an equal sign (=) to assign values to keys.
  • Use a semicolon (;) to separate the key/value pairs

Following statement creates a hash table with three keys.

PS > $hash = @{ Number = 1; Shape = "Square"; Color = "Blue"}

To create an empty hash table in the value of the $hash, type

PS > $hash = @{}

When assigning an ordered hash table to a variable, place the [ordered] attribute before the “@” symbol.

PS > $hash = [ordered]@{ Number = 1; Shape = "Square"; Color = "Blue"}

To display a hash table that is saved in a variable, type the variable name

PS > $hash

Hash tables have Keys and Values properties. Use dot notation to display all of the keys or all of the values.

PS > $hash.keys

PS > $hash.values

To display the number of key/value pairs in the hash table, use a count property as follows:

PS > $hash.count

To add new key/value pairs, use Add method has the following:

$hash.Add("Time", "Now")

You can also use the following statement format

PS > $hash["Time"] = "Now"

PS > $hash = $hash + @{Time="Now"}

You can also add values that are stored in variables.

PS > $t = "Today"
PS > $now = (Get-Date)

PS > $hash.Add($t, $now)

To remove keys, use Remove method has the following:

PS > $hash.Remove("Time")