Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.

If you own the book already, login here to get free, online, searchable access to the entire book's content.

If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".

7.5 Sort an Array or List of Items

Problem

You want to sort the elements of an array or list.

Solution

To sort a list of items, use the Sort-Object cmdlet:

PS > Get-ChildItem | Sort-Object -Descending Length | Select Name,Length

Name                       Length
----                       ------
Convert-TextObject.ps1       6868
Select-FilteredObject.ps1    3252
Get-PageUrls.ps1             2878
Get-Characteristics.ps1      2515
Get-Answer.ps1               1890
New-GenericObject.ps1        1490
Invoke-CmdScript.ps1         1313

Discussion

The Sort-Object cmdlet provides a convenient way for you to sort items by a property that you specify. If you don’t specify a property, the Sort-Object cmdlet follows the sorting rules of those items if they define any.

The Sort-Object cmdlet also supports custom sort expressions, rather than just sorting on existing properties. To sort by your own logic, use a script block as the sort expression. This example sorts by the second character:

PS > "Hello","World","And","PowerShell" | Sort-Object { $_.Substring(1,1) }
Hello
And
PowerShell
World

If you want to sort a list that you’ve saved in a variable, you can either store the results back in that variable or use the [Array]::Sort() method from the .NET Framework:

PS > $list = "Hello","World","And","PowerShell"
PS > $list = $list | Sort-Object
PS > $list
And
Hello
PowerShell
World
PS > $list = "Hello","World","And","PowerShell"
PS > [Array]::Sort($list)
PS > $list
And
Hello
PowerShell
World

In addition to sorting by a property or expression in ascending or descending order, the Sort-Object cmdlet’s -Unique switch also allows you to remove duplicates from the sorted collection.

For more information about the Sort-Object cmdlet, type Get-Help Sort-Object.