PowerShell: Hashtable, Dictionary

By Xah Lee. Date: . Last updated: .

A hashtable is a collection of key and value pairs. Each key is unique.

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

PowerShell Hashtable, Dictionary