How to Sort and Filter in PowerShell

Stewart Beam

How to Sort and Filter in PowerShell

How to Sort and Filter in PowerShell

Output to our terminal from PowerShell commands might need to be sorted to order and limit the number of results returned. Two commands that help with this are Sort-Object and Select-Object. Lets show a simple example and then get more detail.

A Default Example of Get-Process

Running the Get-Process Command in PowerShell produces a table of output with 7 columns. These are sorted by a property “ProcessName” in alphabetical order. Below we snip out the first 5 processes listed when we run the default command. Also, keep in mind that the output of this command will scroll for pages.

Sorting by a Parameter

In the first example we can see that the table has headers (Parameters). We now use the PowerShell Pipeline to sort by any of those Parameters. In the example below we pipe the first command output to a second command Sort-Object. We sort in the example by the column CPU. Below we show one example default, and one with a “Descending” flag.

In the first example the output starts with the lowest CPU and proceeds to the highest. With the “Descending” flag it starts with the highest and moves to the lowest. We still end up with a scrolling page of results, and 7 total columns of data.

Filtering / Selecting Only the Output We Want

What if we only need the first 10 processes listed with the highest CPU Value? This is where our next pipeline command is used. Select-Object will allow us to select only those parameters, or objects that we want to display. The example below selects only the first 10 processes.

We still have 7 columns of data. What if we only need 3 of the parameters that are listed?

Filtering / Selecting the Parameters We Want

The ProcessName, ID, and CPU are the only parameters we are interested in, so lets modify our Select-Object command to get the final output we want. We select only the objects we want, and the number of them we want.

Piping our original output to two more commands allowed us to sort and select the output we want. Additionally, this can be done with other PowerShell commands and allows a simple method to get the output we need.

What if I Need More Options?

Combine these commands with the Get-Help command to see more available options for working with the output you have. Lastly, Use the Get-Member command to learn more about the objects you get as output.