Powershell

Hash table

is a key=value pair data structure in Powershell. This is how to create one:

$names = @{ one = 'Otto'; two = 'Tom'; three = 'John'}

or even nicer - like this the semicolons may be omitted:

$names = @{
    one = 'Otto'
    two = 'Tom'
    three = 'John'
}

Important: the item order is not guaranteed! If the order is important make it ordered:

$names = [Ordered]@{
    one = 'Otto'
    two = 'Tom'
    three = 'John'
}

Adding new items

$names.four = "Anna"
$names["five"] = "Maria" 
$names.add("six", 'Jana') 

Deleting items

$names.remove('four')
# note that using non-existent keys won't produce an error
Write-host "removed '$($names['four'])' from names"  # removed '' from names

Printing values

write-host $names["one"]  # Otto
write-host $names.one     # Otto
write-host "this won't work as expected: number = $names['one']"  # System.Collections.Specialized.OrderedDictionary['one']
write-host "but this will: number = $($names['one'])"
write-host "also this: number = $($names.one)"

Looping

foreach($number in $names.keys) {
    write-host $number
    write-host $names.$number
    write-host "number: $number, name using dot notation: $($names.$number),  name using brackets: $($names[$number])";
    write-host ""
}

# alternative using pipe
$names.getEnumerator() | % {
    Write-host $($_.Key)
    Write-host $($_.Value)
}

# or just
$names.keys | % {
    write-host "number: $_, name: $($names.$_)"
}