Problem
You have a hashtable of keys and values, and want to get the list of values that result from sorting the keys in order.
Solution
To sort a hashtable, use the GetEnumerator() method on the hashtable to gain access to its individual elements. Then use the SortObject cmdlet to sort by Name or Value.
foreach($item in $myHashtable.GetEnumerator() | Sort Name)
{
$item.Value
}
Discussion
Since the primary focus of a hashtable is to simply map keys to values, you should not depend on it to retain any ordering whatsoever—such as the order you added the items, the sorted order of the keys, or the sorted order of the values.
This becomes clear in Example 113.
Example 113. A demonstration of hashtable items not retaining their order
PS >$myHashtable = @{} PS >$myHashtable["Hello"] = 3 PS >$myHashtable["Ali"] = 2 PS >$myHashtable["Alien"] = 4 PS >$myHashtable["Duck"] = 1 PS >$myHashtable["Hectic"] = 11
PS >$myHashtable
Name
Value
Hectic
11
Duck
1
Alien
4
Hello
3
Ali
2
However, the hashtable object supports a GetEnumerator() method that lets you deal with the individual hashtable entries—all of which have a Name and Value property. Once you have those, we can sort by them as easily as we can sort any other PowerShell data. Example 114 demonstrates this technique.
Example 114. Sorting a hashtable by name and value
PS >$myHashtable.GetEnumerator() | Sort Name
Name Value
Ali 2 Alien 4 Duck 1 Hectic 11 Hello 3
PS >$myHashtable.GetEnumerator() | Sort Value
Name Value
Duck 1 Ali 2 Hello 3 Alien 4 Hectic 11