PowerShell Custom Order Sorting
You can use Array.IndexOf()
, which effectively translates strings into numbers:
$importance = "Failed", "Warning", "Success"
$result | Sort-Object { $importance.IndexOf($_.Result) }
Catch: Any unexpected value in Result
will be sorted to the top, because IndexOf
will return -1 for values it can't find.
Test:
$importance = "Failed", "Warning", "Success"
$list = @(
@{ Result = "Warning" }
@{ Result = "Success" }
@{ Result = "Failed" }
)
$list | Sort-Object { $importance.IndexOf($_.Result) }
Result:
Name Value ---- ----- Result Failed Result Warning Result Success
Here is a script block option:
ForEach ($Result in 'Success','Warning','Failed') {
$Obj | Where-Object {$_.Result -eq $Result } | Sort-Object Name
}
Assumes that your cmdlet has output the original object into a variable named $Obj
.