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".

Hashtables (Associative Arrays)

Hashtable Definitions

PowerShell hashtables (also called associative arrays) let you associate keys with values. To define a hashtable, use the syntax:

$myHashtable = @{}

You can initialize a hashtable with its key/value pairs when you create it. PowerShell assumes that the keys are strings, but the values may be any data type.

$myHashtable = @{ Key1 = "Value1"; "Key 2" = 1,2,3; 3.14 = "Pi" }

To define a hashtable that retains its insertion order, use the [ordered] cast:

$orderedHash = [ordered] @{}
$orderedHash["NewKey"] = "Value"

Hashtable Access

To access or modify a specific element in an associative array, you can use either the array-access or property-access syntax:

$myHashtable["Key1"]

returns "Value1".

$myHashtable."Key 2"

returns the array 1,2,3.

$myHashtable["New Item"] = 5

adds "New Item" to the hashtable.

$myHashtable."New Item" = 5

also adds "New Item" to the hashtable.