Getting the Right Output in PowerShell

At times when you wish to get a particular output, you get more than you asked. The default output will at times give you exactly what you want, or a little more than you can chew. In this tutorial, we will show you how to get the exact output you are looking for in PowerShell.

Setup

If you have not already done so, click open Windows PowerShell ISE.

Step one.

Say you want to list out the processes currently running. You would simply type in, Get-Process, within the command pane. While the long list of results is great, maybe you want it shown in a table. So you would pipe the results and format them into a table.

You can do so by running the following command:

Example


    Get-Process | Format-Table

    

Copy and Try it

You may also specify if you only want the name and id properties by adding the following to the end of the above command:

Example


    -property name, id

    

Copy and Try it

So as a whole you would run this and will receive the results listed by name and id within an organized table rather than a long list.

Step two.

You can also put in conditional selectors, or filters. The following pipes the processes, into a selector that selects only the processes whose ID is greater than 1000, then pipes that into a table formatter that selects the Name, CPY and Id properties.

Example


    Get-Process | Where-Object {$_.Id "gt 1000} | Format-Table "property Name,
    CPU, Id

     

Copy and Try it

The Where-Object cmdlet can be thought of as a filter. This particular cmdlet is also aliased as Where, so no worries, either way you type it out, the functionality is the same.

Apart from being able to filter the results before piping, you may also sort results.

Sorting results is implemented like the code below presents:

Example

Get-Process | Where-Object {$_.Id "gt 1000} | Select-Object Name, CPU, Id |
Sort-Object, Id

Copy and Try it

Remarks last but not least…

As you can see, returning objects instead of text is actually far more powerful. Depending on what you are looking for, piping commands shortens the length of code. If this were done in PowerShell scripts rather than commands, it would take many lines of code. As you see, everything was done in one line, just keep in mind, not everything in PowerShell can be done in the command prompt. Join us next time for additional Windows PowerShell tutorials.