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 
 HIDDEN 
 HIDDEN 
 HIDDEN 
 HIDDEN 
Running WlanSvc WLAN AutoConfig 
Stopped wlidsvc Microsoft Account Sign-in Assistant 
Stopped WebClient WebClient 

Using Powershell to Change Network Settings

When administering Server 2012 without the GUI these come in very handy to know:


#Set an IPAddress
New-NetIPAddress -InterfaceAlias 'vEthernet' -IPAddress '172.16.1.1' -PrefixLength 24 -Verbose

#Set DNS Information
Set-DnsClientServerAddress -InterfaceAlias 'vEthernet' -ServerAddresses 172.16.1.2

#Change Network Profile
Get-NetConnectionProfile -Name 'Unidentified network' | Set-NetConnectionProfile -NetworkCategory Private -Verbose