I have a simple script that runs a cmdlet of a 3rd party application and outputs a table with 3 columns - Name
, Result
, JobName
. Result
only contains one of three values: Success
, Warning
, or Failed
.
Output:
Name Result JobName
---- ------ -------
server1 Success servers-A
server2 Success servers-A
server3 Warning servers-A
server4 Success servers-A
server5 Warning servers-B
server6 Success servers-B
server7 Failed servers-C
server8 Failed servers-C
What I'd like to do is sort the table by the Result
column but in the following custom order (order of importance): Failed
, Warning
, then Success
.
Example
Name Result JobName
---- ------ -------
server7 Failed servers-C
server8 Failed servers-C
server3 Warning servers-A
server5 Warning servers-B
server1 Success servers-A
server2 Success servers-A
server4 Success servers-A
server6 Success servers-B
How can this be achieved?
The default is ascending order. To sort multiple properties with different sort orders, use a hash table. For example, with a hash table you can sort one property in ascending order and another property in descending order. To sort objects, send them down the pipeline to Sort-Object .
To sort the output in the PowerShell you need to use Sort-Object Pipeline cmdlet. In the below example, we will retrieve the output from the Get-Process command and we will sort the, according to memory and CPU usage.
The first way to do this is to use the Sort-Object cmdlet (Sort is an alias for the Sort-Object cmdlet). The second way to sort an array is to use the static Sort method from the System.
In JavaScript, we use the sort() function to sort an array of objects. The sort() function is used to sort the elements of an array alphabetically and not numerically. To get the items in reverse order, we may use the reverse() method.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With