Powershell Set Operations
Set operations can do filtering, ordering,grouping and selecting operations on collection of objects that are passed to them.
Filtering (Where-Object)
The Get-Service
cmdlet gets objects that represent the services on a computer. Now, I want to show you how to filter Get-Service
result set.
Get-Service|Where-Object name -eq “MSSQLSERVER”
And these are synonyms:
Get-Service|Where name -eq “MSSQLSERVER”
Get-Service|? name -eq “MSSQLSERVER”
More than one criteria to add in filter.
Get-Service|Where-Object {$PSItem.Name -like “*sql*” -and $PSItem.Status -eq “Running”}
Ordering (Sort-Object)
We can sort Get-Service
cmdlet result set with sort-object.
Get-Service|Sort-Object name # sort by name
Get-Service|Sort-Object Status # sort by Status
We can use descending order.
Get-Service|Sort-Object -Descending Name
This is synonym of Sort-Object
Get-Service|Sort -Descending Name
Grouping(Group-Object)
We can group the Get-Service cmdlet with Group-Object.
Get-Service|Group-Object Status
Selecting(Select-Object)
We can select specified properties of a Get-Service cmdlet with Select-Object.
Get-Service|Select-Object Name
We can choose more than one properties.
Get-Service|Select-Object Name,ServiceType,Status
If you want to see first N record, you should use -First parameter. This sample shows us top 10 records.
Get-Service|Select-Object -First 10 Name,ServiceType,Status
If we want to show all properties we may use select * (like sql). In this sample we can see first record’s all properties.
Get-Service|Select-Object -First 1 *
The synonym is Select.
Get-Service|select Name,ServiceType,Status
All in one sample:
Get-Service|where name -like ‘M*’|sort Name|select -first 5 Name,Status,StartType|group-object Status
Below sample.It gets, name start with ‘M’ services then sort by Name properties and select first 5 records. At the end, it groups by Status property.