Question Details

No question body available.

Tags

powershell sorting powershell-5.1

Answers (2)

February 6, 2026 Score: 5 Rep: 66,419 Quality: Medium Completeness: 80%

You can achieve stable sorting by using 2 sorting expressions, for example:

# This
1..20 | Sort-Object { $ % 2 -eq 0 }, { $ }

Or this

1..20 | Sort-Object @{ Expression = { $ % 2 }; Descending = $true }, { $ }

Alternatively, using a single expression that creates a ValueTuple (comparable structure):

1..20 | Sort-Object { [System.ValueTuple[bool, int]]::new($ % 2 -eq 0, $) }

OrderBy and OrderByDescending from LINQ also perform stable sorting:

[System.Linq.Enumerable]::OrderByDescending(
    [int[]] (1..20),
    [System.Func[int, int]] { $args[0] % 2 })

A caveat is that if the incoming collection is not already ordered you might need to also apply ThenBy or the ValueTuple example, in which case the simplest alternative is using Sort-Object.

[int[]] $collection = 1..20 | Sort-Object { Get-Random }

[System.Linq.Enumerable]::ThenBy( [System.Linq.Enumerable]::OrderByDescending( $collection, [System.Func[int, int]] { $args[0] % 2 }), [System.Func[int, int]] { $args[0] })

There are more ways to achieve the same stable sorting, for example using ValueTuple, a custom Comparer and Array.Sort, honestly not worth using in PowerShell due to their complexity...

February 6, 2026 Score: 4 Rep: 21,460 Quality: Medium Completeness: 70%

To sort the collection in a stable manner do the following:

  • Attach an index to each item in the collection.
  • Sort your collection and use the index as the last sorting criteria in ascending order.
  • Remove the index from each item.

In practice this could look like this:

1..20 ` | ForEach-Object -Begin {$Index = 0} -Process { @{Index = $Index; Value = $} $Index++ } ` | Sort-Object ( @{Expression = { $.Value % 2 }; Descending = $true}, @{Expression = { $.Index }; Ascending = $true} ) ` | ForEach-Object {$.Value}

1 3 5 7 9 11 13 15 17 19 2 4 6 8 10 12 14 16 18 20