Define hash tables in Windows PowerShell Scripts

Completed

A hash table represents a similar concept to an array since it stores multiple items. However, unlike an array which uses an index number to identify each item, a hash table uses for this purpose a unique key. The key is a string that's a unique identifier for the item. Each key in a hash table is associated with a value.

The following table depicts how an array can store a list of IP addresses.

Table 1: How an array stores a list of IP addresses

Index number Value
0 172.16.0.10
1 172.16.0.11
2 172.16.0.40

If the array is named $ip, then you access the first item in the array by using:

$ip[0]

You can use a hash table to store both IP addresses and the computer names as the following table depicts.

Table 2: Using a hash table to store IP addresses and computer names

Key Value
LON-DC1 192.168.0.10
LON-SRV1 192.168.0.11
LON-SRV2 192.168.0.12

If the hash table is named $servers, then you access the first item in the hash table by using either of the following options:

$servers.'LON-DC1'
$servers['LON-DC1']

Note

You only need to use single quote marks to enclose keys that contain special characters. While the hyphen, as part of a file name, isn't a special character, you could use single or double quotes to encapsulate the name if you were concerned. Use single quotes to prevent evaluation, and double quotes to allow evaluation of variables.

Ordered dictionaries

By default, hash tables don't guarantee the order in which keys are displayed. If you need keys to appear in a consistent order—for example, in reports or structured output—use the [ordered] type accelerator to create an ordered dictionary:

$servers = [ordered]@{"LON-DC1" = "192.168.0.10"; "LON-SRV1" = "192.168.0.11"}

Ordered dictionaries behave like hash tables except that keys are always listed in the order you defined them.

Note

Place [ordered] immediately before @{}, not before the variable name.