Using the Sort-Object Cmdlet

Sorting Returned Data

If you’re a script writer you’ve no doubt fantasized about being able to easily sort data any way you want to. Who said dreams never come true? In Windows PowerShell it’s amazingly easy to sort data, and to sort it any way you want.

For example, by default the Get-EventLog cmdlet returns data sorted by the time the event was written to the event log. But what if you’d prefer to sort data by the EventID. What then?

What then, indeed. To sort by EventID just retrieve your data and then pipe it to the Sort-Object cmdlet, telling Sort-Object which property to sort on:

Windows PowerShell also allows you to sort by multiple properties: just separate the properties using commas. For example, suppose you retrieve a list of all the files in the folder C:\Scripts. You’d like to first sort the data by file extension and then by file size; in other words, you want to group all the .txt files together, then sort that little grouping by file size. Here’s the command (using the Get-ChildItem cmdlet) that can pull that off:

And here’s the kind of output you’ll get. Notice that not only are all the .vbs files listed together, but they are also arranged by file size, with the smallest .vbs file listed first and the largest .vbs file listed last: