- 1 year ago
PowerShell: Sort-Object descending wrong order
If you're experiencing issues with the Sort-Object
cmdlet in PowerShell returning the wrong order when using the -Descending
parameter, it may be due to the data type of the objects being sorted. By default, Sort-Object
performs a string-based comparison, which can yield unexpected results for numeric or date/time values.
To ensure the correct sorting order, you can specify the data type explicitly using the -Property
parameter of Sort-Object
. Here's an example:
powershell# Sorting numeric values in descending order
$numbers = 10, 5, 20, 3, 15
$sortedNumbers = $numbers | Sort-Object -Property { $_ } -Descending
$sortedNumbers # Output: 20, 15, 10, 5, 3
# Sorting date/time values in descending order
$dates = Get-Date, (Get-Date).AddDays(-1), (Get-Date).AddDays(1)
$sortedDates = $dates | Sort-Object -Property { $_ } -Descending
$sortedDates # Output: Tomorrow, Today, Yesterday
In the examples above, the -Property { $_ }
syntax is used to specify that the sorting should be based on the actual values of the objects, rather than the default string comparison.
By explicitly specifying the data type and property to sort on, you can ensure that the Sort-Object
cmdlet behaves as expected and returns the correct descending order.