Hello!
PowerShell’s Hash Tables are unordered. The keys don’t always come back in the same order you entered them:
PS /Users/adam/Local/fiddle> $HashTable = @{ >> 'a' = 1 >> 'b' = 2 >> 'c' = 3 >> 'd' = 4 >> } PS /Users/adam/Local/fiddle> $HashTable Name Value ---- ----- c 3 b 2 d 4 a 1
I created the hash in the order a, b, c, d but I got back c, b, d, a. That’s normal.
PowerShell also has Ordered Dictionaries that work like Hash Tables but preserve order:
PS /Users/adam/Local/fiddle> $OrderedDictionary = [ordered]@{ >> 'a' = 1 >> 'b' = 2 >> 'c' = 3 >> 'd' = 4 >> } PS /Users/adam/Local/fiddle> $OrderedDictionary Name Value ---- ----- a 1 b 2 c 3 d 4
Today I had large hash and I needed to convert it to a dictionary that was sorted by key name. The hash was returned by a library I didn’t control so I couldn’t just re-define it as a dictionary. I had to convert it. There are a couple ways, but I found this was the cleanest:
$HashTable = @{ 'd' = 4 'a' = 1 'b' = 2 'c' = 3 } $OrderedDictionary = [ordered]@{} foreach ($Item in ($HashTable.GetEnumerator() | Sort-Object -Property Key)) { $OrderedDictionary[$Item.Key] = $Item.Value } $OrderedDictionary
This outputs a dictionary that has been sorted by its keys:
PS /Users/adam/Local/fiddle> ./Ordering.ps1 Name Value ---- ----- a 1 b 2 c 3 d 4
Because it’s a dictionary and not a regular hash, it’ll keep that ordering.
Happy scripting!
Adam
Need more than just this article? I’m available to consult.
You might also want to check out these related articles: