PowerShell: Sort Hashtable

By Xah Lee. Date: . Last updated: .

Sort Hashtable by Key

# Sort Hashtable by Key

$xx = [ordered] @{
"b" = 2
"a" = 1
}

$yy = ($xx. getenumerator() | Sort-Object -Property key)

Write-Host $yy
# [a, 1] [b, 2]

# return a array
Write-Host $yy.gettype()
# System.Object[]

# type of element
Write-Host $yy[0].gettype()
# System.Collections.DictionaryEntry

# get the key
Write-Host $yy[0].key
# a

# get the value
Write-Host $yy[0].value
# 1

Sort Hashtable by Value

# Sort Hashtable by value

$xx = [ordered] @{
"a" = 7
"b" = 6
"c" = 0
"d" = 9
"e" = 8
}

$yy = ($xx. getenumerator() | Sort-Object -Property value)

Write-Host $yy
# [c, 0] [b, 6] [a, 7] [e, 8] [d, 9]

PowerShell Hashtable, Dictionary