Windows PowerShell also includes
hashtables, or associative arrays. Hashtables use key/value pairs
instead of a numeric index to access the elements.
You can create a hashtable by placing one or more key/value pairs inside @{}.
PS > $hashTable = @{"FirstName"="Jean-Luc";"LastName"="Picard"}
PS > $hashTable
Name Value
---- -----
FirstName Jean-Luc
LastName Picard
You can access specific elements in a hashtable in
two ways: using dot notation or by typing the key within square
brackets. Here’s how to use dot notation:
PS > $hashTable.FirstName
Jean-Luc
PS > $hashTable.LastName
Picard
And here’s the square bracket form:
PS > $hashTable["FirstName"]
Jean-Luc
PS > $hashTable["LastName"]
Picard
You can also send a hashtable down a pipeline and use the Select-Object cmdlet to retrieve specific elements.
PS > $hashTable | Select @{Name="Name";Expression={$_["FirstName"]}}
Name
----
Jean-Luc
To change a key/value pair in a hashtable, you can use either form to access it and assign the new value, as in these examples:
PS > $hashTable.FirstName = "William"
PS > $hashTable["LastName"] = "Riker"
PS > $hashTable
Name Value
---- -----
LastName Riker
FirstName William
You can also store multiple hashtables in an array. In this example, we store two hashtables in an array.
PS > $hashTable = @{"FirstName"="Jean-Luc";"LastName"="Picard"},
@{"FirstName"="William";"LastName"="Riker"}
PS > $hashTable
Name Value
---- -----
LastName Picard
FirstName Jean-Luc
LastName Riker
FirstName William
When multiple hashtables are
in an array, to access elements in the hashtable, you need to index
into a specific element; otherwise, Windows PowerShell will not know
which element you want to retrieve.
PS > $hashTable[0]
PS > $hashTable[0].FirstName
Name Value
---- -----
LastName Picard
FirstName Jean-Luc
In this example, we retrieve the first hashtable in the array and return the key/value pair.