fbpx Sort a Hashtable by Key or Value in Windows PowerShell | Windows PowerShell, Windows Server | HostingUltraso.com
24/7/365 Support

Sort a Hashtable by Key or Value in Windows PowerShell

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

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say