Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.

If you own the book already, login here to get free, online, searchable access to the entire book's content.

If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".

7.13 Create a Hashtable or Associative Array

Problem

You have a collection of items that you want to access through a label that you provide.

Solution

To define a mapping between labels and items, use a hashtable (associative array):

PS > $myHashtable = @{ Key1 = "Value1"; "Key 2" = 1,2,3 }
PS > $myHashtable["New Item"] = 5
PS >
PS > $myHashTable

Name                           Value
----                           -----
Key 2                          {1, 2, 3}
New Item                       5
Key1                           Value1

Discussion

Hashtables are much like arrays that let you access items by whatever label you want—not just through their index in the array. Because of that freedom, they form the keystone of a huge number of scripting techniques. Because they let you map names to values, they form the natural basis for lookup tables such as those for zip codes and area codes. Because they let you map names to fully featured objects and script blocks, they can often take the place of custom objects. And because you can map rich objects to other rich objects, they can even form the basis of more advanced data structures such as caches and object graphs.

The Solution demonstrates how to create and initialize a hashtable at the same time, but you can also create one and work with it incrementally:

PS > $myHashtable = @{}
PS > $myHashtable["Hello"] = "World"
PS > $myHashtable.AnotherHello = "AnotherWorld"
PS > $myHashtable

Name                           Value
----                           -----
AnotherHello                   AnotherWorld
Hello                          World

When working with hashtables, you might notice that they usually list their elements out of order—or at least, in a different order than how you inserted them. To create a hashtable that retains its insertion order, use the [ordered] type cast as described in Recipe 7.14.

This ability to map labels to structured values also proves helpful in interacting with cmdlets that support advanced configuration parameters, such as the calculated property parameters available on the Format-Table and Select-Object cmdlets. For an example of this use, see Recipe 3.2.

For more information about working with hashtables, see “Hashtables (Associative Arrays)”.

See Also

Recipe 3.2, “Display the Properties of an Item as a Table”

Recipe 7.14, “Sort a Hashtable by Key or Value”

“Hashtables (Associative Arrays)”