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
PS>$pets = @{} PS>
PS>$pets = @{Cat = 'Frisky'; Dog = 'Spot'; Fish = 'Nimo'; Hamster = 'Whiskers'} PS>
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>
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>
PS>$pets.Remove('Hamster') PS>
foreach($pet in $pets.keys) { $pet # Print each Key $pets.$pet # Print value of each Key }
The Format-Table cmdlet formats hash table output as a table:
PS>$pets | Format-Table
The Format-List cmdlet formats hash table output as a list of separate key-value pairs.:
PS>$pets | Format-List