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.
- Hashtable is unordered.
- Dictionary is the ordered version of hashtable.
Create hashtable (unordered)
type is 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]
Create dictionary (Ordered)
type is 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
Get Total Count (Length)
$dict = [ordered] @{"a" = 1; "b" = 2; } $dict.count # 2
or
$dict = [ordered] @{"a" = 1; "b" = 2; } $dict.a # 1