In the previous post you learned how to extract more information from your objects than the default view allows. So we learned how to use Select-Object with the -Property parameter to display specific columns (properties) in your output.
Today I’m going to show you how to sort that output. You probably noticed that PowerShell sorts by the Name property by default. Which is fine but what happens if you wanted to sort on a different property such as hostname of the computer returning the service?
It’s all about Sort-Object baby!
So remember the pipeline – you can keep stringing cmdlets together to fine tune your output.
So I can do this:
gsv dhcp -computername dc16alx1, ws11alx1 | select -property name, status, machinename | sort -Property machinename
This might look confusing at first but break it down:
- Get all the DHCP services from computers with hostname dc16alx1 and ws11alx1.
- Pipe that result to select-object and only display columns for the Name, Status and MachineName (the hostname).
- Pipe that result to sort and sort the output in ascending order on the machinename property. By ascending order I mean the natural path of the alphabet (A, B, C, etc… going forward)
If you wanted to sort in descending order just use the
One thing to keep in mind is that when you pipe an object to Select-Object the object is modified so that it only has the properties specified in the
-Property parameter. So if you try to sort on a property that belongs to the cmdlet but you’ve filtered it out with Select-Object it won’t sort. That’s why it’s always a good idea to pipe the cmdlet to Get-Member so you can think about exactly what kind of data you’re trying to view.
In the next post we’ll look into filtering out specific values using
Where-Object (the alias is %). Using this with Select and Sort will give you the maximum power for building awesome PowerShell scripts and one-liners.