0
0
PowershellHow-ToBeginner · 3 min read

How to Use Sort-Object in PowerShell: Syntax and Examples

Use the Sort-Object cmdlet in PowerShell to sort objects by one or more properties. You specify the property name(s) after -Property, and optionally use -Descending to reverse the order. This cmdlet works with any objects that have properties.
📐

Syntax

The basic syntax of Sort-Object is:

  • Sort-Object -Property <propertyName>: Sorts objects by the specified property in ascending order.
  • -Descending: Optional switch to sort in descending order.
  • -Unique: Optional switch to return only unique objects after sorting.
  • -CaseSensitive: Optional switch to make sorting case-sensitive.
powershell
Sort-Object -Property <propertyName> [-Descending] [-Unique] [-CaseSensitive]
💻

Example

This example sorts a list of numbers in ascending and then descending order. It shows how to use Sort-Object with the -Property and -Descending parameters.

powershell
$numbers = @(5, 3, 9, 1, 4)

# Sort ascending
$numbers | Sort-Object -Property {$_}

# Sort descending
$numbers | Sort-Object -Property {$_} -Descending
Output
1 3 4 5 9 9 5 4 3 1
⚠️

Common Pitfalls

One common mistake is forgetting that Sort-Object sorts by property names, so sorting simple values requires using a script block like {$_}. Another pitfall is not using -Descending when you want reverse order, or expecting it to sort in place (it outputs sorted objects but does not change the original variable).

Also, sorting complex objects requires specifying the correct property name.

powershell
# Wrong: sorting numbers without property or script block
$numbers = @(5, 3, 9)
$numbers | Sort-Object

# Right: use script block to sort values
$numbers | Sort-Object -Property {$_}
Output
5 3 9 3 5 9
📊

Quick Reference

ParameterDescription
-Property Property name(s) to sort by
-DescendingSort in descending order
-UniqueReturn only unique objects after sorting
-CaseSensitiveSort with case sensitivity
-InputObjectSpecify objects to sort directly

Key Takeaways

Use Sort-Object with -Property to sort objects by their property values.
Add -Descending to sort in reverse order.
For simple values, use a script block like {$_} as the property.
Sort-Object outputs sorted objects; it does not modify the original variable.
Specify correct property names when sorting complex objects.