Wednesday, March 5, 2014

Lets Sort it Out using Sort-Object

Hi, We all used Sort-Object cmdlet one time or another, but generally we use it to sort in two ways based on one property in ascending or descending order, but Sort-Object can do more sophisticated things.


For our demonstration we will use below database, this data is stored in data.csv, we will store this in $data variable to work, and for whole blogpost, I will use Sort alias for Sort-Object.


PS >$data=import-csv .\data.csv
 
NameIDDepartment
John4567Management
Kivell3099Finance
Jardine1234IT
Gill9123Finance
Sorvino434IT
Jones5456Finance
Andrews1209Finance
Jardine2354IT
Thompson724IT
Jones1287Finance
Morgan8614IT
Howard5914Finance
Parent961Management
Jones5964IT
Smith1029Finance

So First of all we want to Sort above output in descending order based on name.



















That was easy, now we want to sort it on ID, let see the output below.



















Looks like, Powershell did something wrong, so what just happened there and why powershell seems to give us wrong sort output.

When we imported the data in PowerShell, all properties were imported as String, when we ask Powershell to sort, it sorts the property based on its type, most of the time it is fine, but sometimes, we have to intervene, this is one of that type.
We would tackle this by telling the Powershell to treat ID property as integer.



















Now, we have generally no issue to sort data based on two property also, if I want to sort data in descending order first for Department then for name so I can use below command

PS > $data | Sort -Property Department, Name -Descending.

But what if i want to sort data based on Department in Ascending order then on based on Name in Descending order, To do this Sort's Property Parameter can take an hashtable where we can mention, Ascnding or Descending order for each property separately.








Happy Scripting...