Hash Table

Arrays and hash tables are two of the most common data structures available in modern scripting languages, and Windows PowerShell supports both of them. An array, which is sometimes referred to as a collection, stores a list of items. A hash table, which is sometimes called a dictionary or an associative array, stores a paired list of items.

Hash tables are useful when you want to store and retrieve items by name


Initializing an Empty Hash Table

PS>$pets = @{} PS>

Initializing a Hash Table

PS>$pets = @{Cat = 'Frisky'; Dog = 'Spot'; Fish = 'Nimo'; Hamster = 'Whiskers'} PS>

Accessing Hash Table Items

To access a value in a hash table, you can specify the hash table's name followed by the name associated with the value, enclosed in square brackets. Alternatively, you can put a period between the hash table's name and the name associated with the value.

$pets.Cat # Frisky $pets.Dog # Spot $pets.Fish # Nimo $pets.Hamster # Whiskers PS>

Adding Items to a Hash Table

PS>$pets.Add('Cat', 'Frisky') PS>$pets.Add('Dog', 'Spot') PS>$pets.Add('Fish', 'Nimo') PS>$pets.Add('Hamster', 'Whiskers') PS>

or

PS>$pets.Cat = 'Frisky' PS>$pets.Dog = 'Spot' PS>$pets.Fish = 'Nimo' PS>$pets.Hamster = 'Whiskers' PS>

Removing Items from a Hash Table

PS>$pets.Remove('Hamster') PS>

Looping Through a Hash Table Using ForEach

foreach($pet in $pets.keys) { $pet # Print each Key $pets.$pet # Print value of each Key }

Format-Table

The Format-Table cmdlet formats hash table output as a table:

PS>$pets | Format-Table

Format-List

The Format-List cmdlet formats hash table output as a list of separate key-value pairs.:

PS>$pets | Format-List