Sorting Arrays

by Feb 11, 2009

Let's assume you have an array of items which you would like to sort. Here is the PowerShell way:

$array = 1,5,32,5,7
$array | Sort-Object
$array = "Hello", "World", "Test", "A", "Z"
$array | Sort-Object

If you'd like to sort the array permanently, you could assign the sort result back to the variable:

$array = $array | Sort-Object

However, this is not very efficient and time consuming. A better way of sorting an array permanently is to use the Sort() method provided by System.Array:

$array = "Hello", "World", "Test", "A", "Z"
[Array]::Sort([array]$array)
$array

This method is almost 10 times faster. Use Measure-Command to analyze performance of different approaches:

Measure-Command {
1..1000 | % {
$array = "Hello", "World", "Test", "A", "Z"
$array = $array | Sort-Object
}
}

Measure-Command {
1..1000 | % {
$array = "Hello", "World", "Test", "A", "Z"
[Array]::Sort([array]$array)
}
}