PowerShell Basics Series - Sorting and Selecting

 May 19, 2016

Once you start using PowerShell, and you start to view the output(s) of your cmdlets, you will quickly find you have a need to sort and filter (select) the results of those PowerShell cmdlets, so today I would like to talk about two of the most common tasks in PowerShell: sorting and selecting your PowerShell objects.

When it come to sorting, PowerShell makes things really easy, with the Sort-Object cmdlet (which is even easier if you use the alias Sort). Using this cmdlet means that we can apply the same sorting principles in our PowerShell code, whether we are working on files, AD objects, processes, services etc. etc. etc. (We will introduce the Select-Object cmdlet in a moment.)

Most cmdlets have a default sort order built in, for example Get-Process and Get-Service both produce their output in ascending name order, while Get-EventLog will sort by time, and there are also a large number of options to modify said sort order, which I will again get to in a moment. But before that, lets digress for a moment to look at a cmdlet that allows us to find out the actual names of the properties of our objects, so that we know exactly which properties we can sort on. That cmdlet is the Get-Member (alias of gm), and, like our sort options, we normally pipe the command output to it ie:

You can see here that the Get-Member cmdlet shows us the various components of the service object, including

  • Properties – the attributes of the service object, eg. the service name, the service status etc.
  • Methods – the actions that can be performed on the object, such as start, stop, pause etc.
  • Events – triggered when something happens to the object, such as when the service is deleted.

And other attribute types such as Aliasproperty or ScriptMethod etc. Other types of objects may have additional object types also but Properties, Methods and Events are the main attribute types, common to most objects, and what we are interested in here is the actual attribute names themselves, so we can reference them in our sorting or other cmdlets.

O.K., so now we have found out the actual object attribute names, we can use those names in our sorting options, such as:

Get-Service | Sort-Object –Property Name –Descending | Select-Object –First 5

Get-Service | Sort Name –Desc | Select –First 5

The first line gets a list of all the services on the local machine (as objects remember?), sorts them by their name property in descending order, and then, just for brevity, I have introduced the Select-Object cmdlet to display just the first 5 services. Interestingly enough, the second line does exactly the same thing, but here I have used alias’s (Sort for Sort-Object, Select for Select-Object) and abreviation (-Desc for –Description). Remember alias’s are great when we are manually typing a simple PowerShell cmdlet, but for scripts etc, it will pay you to use the full cmdlet designator, so others can easily understand the cmdlets we are using.

Expanding upon this, we can even sort on multiple object properties (e.g. Status, Name and DisplayName) as in:

Get-Service | Sort-Object Status, Name, DisplayName | Select-Object –First 5

As a side note here, notice that when we sort by Status, the “Stopped” status displays before the “Running” status. This is because the status is actually stored (and sorted) as a numeric value (Stopped =1, Running=4 etc.). PowerShell just adds a text label to make the displayed output easier for us poor humans to understand.

Here’s another example of sorting on multiple properties (make sure you open PowerShell with Administrative access for this one): Get-EventLog –Newest 10 –LogName Security | Select-Object –Property EventID, TimeWritten, Message

And here are a couple of further examples – see if you can work out what they do?

Get-Process | Sort-Object –Property WS |Select-Object –Last 5

and

cd C:\
Get-ChildItem | Sort-Object –Property Name -Descending

Next, there is a great switch that can be used with the Sort-Object cmdlet that I really love, it is the –Unique switch. Using this switch will return just unique values only, so it is wonderful for eliminating duplicates e.g.:

In the first example, we are simply creating a list of numbers (including duplicates) and piping them into the Sort-Object cmdlet, which, with the –Unique parameter is sorting the numbers into numerical ascending order, and eliminating any duplicates.

The second example is getting the last (or newest) 50 entries from the System event log, and again just showing unique entries from that original list of 50.

Finally, when we use the Sort-Object cmdlet normally, the case doesn’t matter, but again there is a switch to force sorting by case; see the difference between the following 2 examples:

So go ahead and try these examples for yourself an see how easy PowerShell makes it to query services, processes, files and directories, event logs etc. etc. etc. You might also try Help Sort-Object –full to find out other useful parameters to modify or refine your sorts.

Next up in my PowerShell Basic series - Measuring Objects.

How do your Excel skills stack up?   

Test Now  

About the Author:

Gordon Cowser  

With over 22 years real world and training experience, Gordon is our most senior IT Infrastructure trainer. His expertise includes but is not limited to; Microsoft Server and Client OS, Messaging, Collaboration, Active Directory and Network Infrastructure. Gordon also specialises in SharePoint technologies training in both technical and end user aspects. With his extensive skill-set he brings a thorough mentoring capability to the classroom where he can advise on technical issues and challenges often beyond the scope of the course curriculum. A very approachable and experienced training professional, he has the ability to establish credibility fast with students at all levels.

Read full bio
top
Back to top