July 9th, 2007

How to sort the console output of a hashtable in PowerShell

Andrew Arnott
Principal Software Engineer

Hashtables are inherently unsorted, but when you’re printing a hashtable’s contents to the console, it can certainly be helpful to sort its contents by key.  Although it’s not obvious, the way to do it is pretty easy.

Let’s start with defining a hashtable and play with it until it’s obviously unsorted.

PS C:\> $h = @{b=2;a=3;c=1}
PS C:\> $h

Name                           Value
----                           -----
a                              3
b                              2
c                              1


PS C:\> $h['d']=5
PS C:\> $h

Name                           Value
----                           -----
a                              3
b                              2
d                              5
c                              1

Great. Now let’s sort it:

PS C:\> $h | sort name

Name                           Value
----                           -----
a                              3
b                              2
d                              5
c                              1

Ergh! What happened? Well, without going into tons of detail, it has to do with the type that backs HashTable and how you can’t sort the object itself. You’ve got to generate a list of key-value pairs and sort that.

Here’s the correct way to do it:

PS C:\> $h.GetEnumerator() | sort name

Name                           Value
----                           -----
a                              3
b                              2
c                              1
d                              5

Great. And yes, sorting by value works too:

PS C:\> $h.GetEnumerator() | sort value

Name                           Value
----                           -----
c                              1
b                              2
a                              3
d                              5

Author

Andrew Arnott
Principal Software Engineer

Principal Software Engineer and OSS contributor. Visual Studio Platform.

0 comments

Discussion are closed.

Feedback