Advanced Sort-Object

Sort-Object can be used in a few ways which allow a very powerful methods for sorting objects in weird and wonderful ways. Here is a simple example:

$Data = Get-Service

#First Alphabetically by Status, Then by Name
$Data | Sort-Object -Property Status,Name


The Property parameter accepts an String or an Object. If we use a Hashtable as input here Sort-Object will look for Expression (A Script Block) and Ascending and Descending (Both Boolean) which can be used to make customize sorting logic. Here some more complex:


#First Where Name Matches ^win, Next by Name Matches ^SQL, The rest Alphabeticaly by name
$Data | Sort-Object -Property @{Expression = {$_.Name -match '^Win'}; Descending = $true}, @{Expression = {$_.Name -match '^SQL'}; Descending = $true},Name

Status Name DisplayName 
------ ---- ----------- 
Running WinDefend Windows Defender Service 
Running WinHttpAutoProx... WinHTTP Web Proxy Auto-Discovery Se...
Running Winmgmt Windows Management Instrumentation 
Running WinRM Windows Remote Management (WS-Manag...
Stopped SQLAgent$SQLEXP... SQL Server Agent (SQLEXPRESS) 
Running SQLBrowser SQL Server Browser 
Running SQLWriter SQL Server VSS Writer 
Stopped AJRouter AllJoyn Router Service 
Stopped ALG Application Layer Gateway Service 
Stopped Apache2.4 Apache2.4 
Running AppHostSvc Application Host Helper Service 


#Conditional Logic to Update an object as part of the sort.
$Data | Sort-Object -Property @{Expression = {If($_.Name -match '^Win'){$_.Name = 'HIDDEN'}}; Descending = $true}

Stopped WerSvc Windows Error Reporting Service 
Stopped WiaRpc Still Image Acquisition Events 
Running WlanSvc WLAN AutoConfig 
Stopped wlidsvc Microsoft Account Sign-in Assistant 
Stopped WebClient WebClient 

Leave a Reply

Your email address will not be published. Required fields are marked *