PowerShell Script to Sort Array Easily
Use
$sortedArray = $array | Sort-Object to sort an array in PowerShell; this command outputs the array elements in ascending order.Examples
Input[5, 3, 8, 1]
Output[1, 3, 5, 8]
Input['banana', 'apple', 'cherry']
Output['apple', 'banana', 'cherry']
Input[]
Output[]
How to Think About It
To sort an array in PowerShell, think of passing the array through a sorting command that compares each element and rearranges them in order. PowerShell's
Sort-Object cmdlet does this by taking the array as input and returning a new sorted array.Algorithm
1
Get the input array.2
Pass the array to the sorting command.3
The sorting command compares elements and orders them ascendingly.4
Return the sorted array.Code
powershell
$array = 5, 3, 8, 1 $sortedArray = $array | Sort-Object Write-Output $sortedArray
Output
1
3
5
8
Dry Run
Let's trace sorting the array [5, 3, 8, 1] through the code
1
Initial array
The array is [5, 3, 8, 1]
2
Sort-Object processes array
It compares elements and rearranges them in ascending order
3
Output sorted array
The sorted array is [1, 3, 5, 8]
| Step | Array State |
|---|---|
| Initial | [5, 3, 8, 1] |
| After sorting | [1, 3, 5, 8] |
Why This Works
Step 1: Input array
The array holds the values we want to sort.
Step 2: Sort-Object cmdlet
Sort-Object takes the array and compares each element to order them.
Step 3: Output
The sorted array is returned and printed with Write-Output.
Alternative Approaches
Using .NET Array Sort method
powershell
$array = 5, 3, 8, 1 [Array]::Sort($array) Write-Output $array
This sorts the array in place but works only on fixed arrays, not on PowerShell collections.
Sorting descending
powershell
$array = 5, 3, 8, 1 $sortedDesc = $array | Sort-Object -Descending Write-Output $sortedDesc
Sorts the array in descending order using the <code>-Descending</code> flag.
Complexity: O(n log n) time, O(n) space
Time Complexity
Sorting uses comparison-based algorithms which typically run in O(n log n) time, where n is the number of elements.
Space Complexity
Sorting creates a new sorted array, so it uses O(n) extra space.
Which Approach is Fastest?
Using Sort-Object is simple and efficient for most cases; .NET's [Array]::Sort can be faster but is less flexible.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sort-Object | O(n log n) | O(n) | General use, easy syntax |
| [Array]::Sort | O(n log n) | O(1) | In-place sorting of fixed arrays |
| Sort-Object -Descending | O(n log n) | O(n) | Sorting in reverse order |
Use
Sort-Object to easily sort arrays in PowerShell without extra code.Forgetting to pipe the array to
Sort-Object and expecting the original array to change in place.