Sometimes the best way to learn something important is to walk the long, rocky road. And sometimes you have to use poor analogies to open a blog post because nothing better is clicking at the moment. But most of the time you wish someone else had walked the long, rocky road for you so you could pilfer the code from their blog and avoid thinking all together. My most recent rocky road, and not the ice cream kind, was sorting a multidimensional array. Or more accurately an ArrayList.

Obviously you can use sort-object to sort an array, but what if the object you want to sort by is not the first property of the array within the ArrayList? Example: say you have four fields in an array. You store 7000 of these arrays in an ArrayList. You want to sort from the last field instead of the first. List objects such as a hashtables don’t like storing and sorting more than two fields. And since you can’t name the columns in an array or ArrayList (that I have found), sorting that multidimensional nightmare appears to be exactly that. A nightmare.

It turns out the solution is pretty easy. This will even work for a regular multidimensional array, and not just an ArrayList. Let’s say your ArrayList is named $x. $x has 7000 arrays and four fields per array. If you want to sort by the fourth field, a.k.a. field [3] in array talk, all you need to do is this:

$x = $x | sort-object @{Expression={$_[3]}; Ascending=$false}

“@{Expression={$_}; Ascending=$false}”, according to the sort-object help file, gives you hashtable like control of your sort. Without the hassle of working with a large hashtable. The expression value lets you do just about anything with that pipeline variable ($_). You can even do math in that expression field. Just look at example 5 in the detailed help output (help sort -detailed). The true/false in the Ascending value just determines whether the sort does big-to-small or small-to-big.

It turns out that sorting multidimensional arrays is as easy as eating rocky road ice cream. So stop walking, pilfer my code, and get on with your multidimensional sorting already.

Written by James Kehr Employee @ SherWeb