Hash Tables
Prerequisites: Arrays
A hash table stores key-value pairs — look up a value by its key instead of by position.
Real-world analogy: a contacts list: you find a number by the person's name, not by where it is in the list.
$ages = @{
Ada = 36
Linus = 28
}
$ages['Ada']
$ages.Linus
$ages['Grace'] = 45
$ages.Count
$ages.ContainsKey('Linus')
$ages.Remove('Linus')
$ages.Keys | Sort-Object
36
28
3
True
Ada
Grace
@{ key = value; ... }creates a hash table. Keys are case-insensitive.- Read with
$h['key']or$h.key; assign to add or change. - Keys come back in no particular order. Use
[ordered]@{ ... }to keep insertion order.
Looping over a hash table
$stock = [ordered]@{ apples = 10; pears = 0; plums = 4 }
foreach ($item in $stock.GetEnumerator()) {
'{0}: {1}' -f $item.Key, $item.Value
}
apples: 10
pears: 0
plums: 4
Counting with a hash table
$counts = @{}
foreach ($word in 'red', 'blue', 'red', 'green', 'red') {
$counts[$word] += 1
}
$counts.GetEnumerator() | Sort-Object Value, Key -Descending | ForEach-Object { "$($_.Value) $($_.Key)" }
3 red
1 green
1 blue
A missing key returns $null, and $null + 1 is 1 — so += 1 works
even the first time a word is seen.
Splatting
A hash table can pass parameters to a command — called splatting
(note the @ instead of $):
$params = @{
Year = 2025
Month = 12
Day = 25
Format = 'dddd'
}
Get-Date @params
Thursday
Splatting keeps long command lines readable, and lets you build up parameters conditionally before calling a command.