PowerShell: Hashtable, Dictionary
A hashtable is a collection of key and value pairs. Each key is unique.
- Key can be any type.
- Value can be any type.
Hashtable elements can be added or removed.
There are ordered and unordered hashtable. The ordered version is often called dictionary.
Create Ordered Hashtable (dictionary)
Ordered is of type: System.Collections.Specialized.OrderedDictionary
# create a dictionary (ordered) $x = [ordered] @{"a" = 1; "b" = 1; } Write-Host $x # [a, 1] [b, 1] Write-Host $x.gettype() # System.Collections.Specialized.OrderedDictionary
Create Unordered hashtable
Unordered hashtable is of type: System.Collections.Hashtable
# create a hashtable (unordered) $x = @{"a" = 1; "b" = 2; } Write-Host $x # [a, 1] [b, 2] Write-Host $x.gettype() # System.Collections.Hashtable
# create a hashtable, when in multiple lines, no need semicolon $x = @{ "a" = 1 "b" = 2 } Write-Host $x # [a, 1] [b, 2]
Get Total Count (Length)
$dict = [ordered] @{"a" = 1; "b" = 2; } $dict.count # 2
or
$dict = [ordered] @{"a" = 1; "b" = 2; } $dict.a # 1