PowerShell Sorting by Multiple Columns

PowerShell's Sort-Object cmdlet is super useful, especially when preparing output for human consumption.  A few people have found my blog while looking for more information about its use, specifically while looking for how to sort by multiple columns (well, properties, technically).  I've never done so (much less written about it), so I hope those folks found answers elsewhere.  But, it got me curious... and it turns out that it's really easy.

The Technet article on Sort-Object has the answer directly spelled out: just use commas to create a list of properties to sort by (in order to precedence).  Let's look at some examples!  First, prepare a variable with some good sortable data:

$myData = get-eventlog System -newest 25

And then we can get to sorting!  Say you want to sort primarily by EntryType (Warning, Information, Error) and then by Source.  Easy-peasy:

$myData | sort EntryType,Source

How about if you want it to be in descending order?  Yeah, there's a switch for that:

$myData | sort EntryType,Source -Descending

Hmm... but that's interesting.  It affected both of the sort properties... what if you only wanted the Source list to be descending?  That takes a little more work, but that same Technet article has the solution.  Just use the following hash table syntax for your properties: @{Expression="Property Name";Descending=$true}.  Let's give it a try!

$myData | sort EntryType,@{Expression="Source";Descending=$true}

There you have it!

Comments

Popular posts from this blog

Clone a Standard vSwitch from one ESXi Host to Another

Deleting Orphaned (AKA Zombie) VMDK Files