How to sort the console output of a hashtable in PowerShell



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.

Great. Now let’s sort it:

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:

Great. And yes, sorting by value works too:

Andrew Arnott

Principal Software Engineer, Visual Studio Platform

Follow Andrew   

No Comments.