TExcelTAD
Home › PowerShell › PowerShell Hashtables

PowerShell Hashtables

A hashtable stores key/value pairs: you look up a value by its key instead of by a position. It's PowerShell's dictionary, used for settings, lookups, counting, building objects and passing parameters (splatting).

Creating and reading

Write a hashtable with @{ }. Separate pairs with new lines or semicolons:

powershell · try it yourself
$capitals = @{
    France  = 'Paris'
    Japan   = 'Tokyo'
    Kenya   = 'Nairobi'
}

$capitals['Japan']
$capitals.Kenya
$capitals.Count
"[$($capitals['Peru'])]"
Tokyo
Nairobi
3
[]

Use either the index syntax $h['key'] or the dot syntax $h.key. A missing key returns $null. Keys are case-insensitive for strings: $capitals.japan works too.

Adding, changing, removing

powershell · try it yourself
$stock = @{}
$stock['apples'] = 10
$stock.pears = 4
$stock.Add('plums', 7)
$stock['apples'] += 5
$stock.Remove('pears')

$stock.ContainsKey('pears')
$stock.ContainsKey('plums')
$stock['apples']

try { $stock.Add('plums', 1) } catch { 'Add failed: the key already exists' }
False
True
15
Add failed: the key already exists

.Add() throws an error if the key exists; plain assignment overwrites silently. Choose the one that matches your intent.

Ordered hashtables

A normal hashtable does not remember the order you inserted keys. When order matters (for display or for JSON output), put [ordered] in front:

powershell · try it yourself
$plain = @{ zebra = 1; apple = 2; mango = 3 }
$sorted = [ordered]@{ zebra = 1; apple = 2; mango = 3 }

$plain.GetType().Name
$sorted.GetType().Name
$sorted.Keys -join ', '
$sorted
Hashtable
OrderedDictionary
zebra, apple, mango

Name                           Value
----                           -----
zebra                          1
apple                          2
mango                          3

[ordered] creates an OrderedDictionary, which keeps insertion order and otherwise works the same way. For predictable output in examples and reports, prefer it.

Looping over a hashtable

A hashtable is a single object in the pipeline, so ForEach-Object would run once. Loop over its keys, or call .GetEnumerator() to get key/value entries:

powershell · try it yourself
$ages = [ordered]@{ Ada = 36; Alan = 41; Grace = 45 }

foreach ($name in $ages.Keys) {
    "$name is $($ages[$name])"
}

$ages.GetEnumerator() |
    Where-Object Value -gt 40 |
    ForEach-Object { "$($_.Key) is over 40" }
Ada is 36
Alan is 41
Grace is 45
Alan is over 40
Grace is over 40

Warning: Don't add or remove keys while looping over $h.Keys; PowerShell throws "Collection was modified". Loop over a copy instead: foreach ($k in @($h.Keys)) { ... }.

Counting with a hashtable

A classic use is counting how often each value appears:

powershell · try it yourself
$words = 'the cat and the dog and the bird' -split ' '
$counts = @{}
foreach ($w in $words) {
    $counts[$w] = $counts[$w] + 1      # $null + 1 is 1
}
$counts.GetEnumerator() | Sort-Object Value, Name -Descending | ForEach-Object {
    '{0,-5} {1}' -f $_.Key, $_.Value
}
the   3
and   2
dog   1
cat   1
bird  1

Nested hashtables

Values can be anything, including arrays and other hashtables, which makes hashtables a natural fit for configuration:

powershell · try it yourself
$config = @{
    App      = 'inventory'
    Ports    = 80, 443
    Database = @{ Host = 'db01'; Name = 'stock' }
}
$config.Database.Host
$config.Ports[1]
$config.Database.Name = 'stock_test'
$config['Database']['Name']
db01
443
stock_test

Test yourself

What does $h = @{a=1}; $h['b'] return?

  1. 0
  2. An error
  3. $null
  4. 'b'

How do you create a hashtable that keeps keys in insertion order?

  1. @{ } always keeps order
  2. [ordered]@{ }
  3. @[ ]
  4. [sorted]@{ }

What happens with $h.Add('x', 1) when key 'x' already exists?

  1. The value is replaced
  2. Nothing
  3. An error is thrown
  4. A second 'x' key is added