Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Wednesday, November 16, 2011

How to sort an object with one property descending and another property ascending with PowerShell?

I’ll admit, I did not come up with the answer to this one.  I pulled it from the help file for Sort-Object  It was a good question though.

get-service | sort-object -property @{Expression="Status";Descending=$true}, @{Expression="DisplayName";Descending=$false}

The above command is all on the same line.

First we used Get-Service to get some objects to work with.  We then piped it to Sort-Object  and we used the –Property parameter to tell PowerShell what values we are interested in sorting.

 

Next we switch to creating a hash table to specify that we first want to sort the Status property in descending order.  We do this by setting the Descending flag to Boolean True  In PowerShell Boolean true is $true and Boolean false is $false.  We the specify the next value that we want to sort by which is DisplayName and we set the Descending flag to Boolean $false.

 

The end result is a list of all running processes that is sorted in descending order by status and then ascending order by DisplayName.

No comments: