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.

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

PowerShell Hashtable, Dictionary

key-and-value data types in programing languages