How to sort the output in PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

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.

Example

Get-Process | Sort-Object WorkingSet | Select -First 10

Output

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
      0       0       60          8                 0   0 Idle
    144       8     1840        232       0.14   8396   1 SkypeBackgroundHost
    514      26    19280        300       0.73  16872   1 Calculator
   1140      50    63584        464      15.86  10688   1 ksdeui
     53       3     1212        816       0.30    580   0 smss
    217      17     3432       1848      37.03  13272   1 ptim
    486      26     7404       2228     168.86  13732   1 ptsrv
     32       6     1636       2440       0.16   1092   0 fontdrvhost
     86       5      968       3620       0.00   1060   0 svchost
     85       6     1208       4104       0.59   4116   0 ibtsiva

In the above example, the output is stored into ascending order which is the default order and then we have retrieved the first 10 processes.

If you want to output in Descending order then you need to add the parameter − Descending.

Example

Get-Process | Sort-Object WorkingSet -Descending | Select -First 10

Output

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
     -------  ------    -----      -----     ------     --  -- -----------
           0       0     3660     719552     544.86   2580   0 Memory Compression
         968     125  1132200     487196   6,867.28   4228   1 chrome
        1867     150   294740     332516   1,136.42  19036   1 WINWORD
        1137      46   446876     305092   2,470.48  14560   1 chrome
         583      38   309476     250312     755.97  15652   1 chrome
        3597     107   275080     226752  11,615.69  12712   1 chrome
         464      59   179012     172652   1,938.55  18732   1 chrome
         350      31   191756     157716     339.11   5952   1 chrome
         607      61   129380     156224     106.52   7712   1 Code
         536      31   186496     146176      35.81  10352   1 Code

Similarly, you can sort CPU and other properties as well in the ascending / descending order as shown in the below example.

Example

Get-Process | Sort-Object CPU | Select -First 10
Get-Process | Sort-Object CPU -Descending | Select -First 10
raja
Published on 07-Apr-2020 12:01:06
Advertisements