Sorting objects in Windows Powershell

We can sort the objects based on specific property.

For example – “Get-Process” command shows the output where the objects are sorted by process name. But if you want to sort by other property say “handles”, you can use below syntax.

Get-Process | Sort-Object handles

Sorting based on specific column

You can also sort the files based on any column.

Below example shows that we are sorting the files by first column. To sort by second column, just replace “0” by “1” and so on.

> Get-Content ./cities.txt | Sort-Object { $_.split()[0] } -Descending

Below example shows that we are sorting the files by first column but numerically. Note that we have casted the first column value to integer. To sort by second column, just replace “0” by “1” and so on.

> Get-Content ./cities.txt | Sort-Object { [int]$_.split()[0] } -Descending

You may also like...