PowerShell Pipeline

The PowerShell pipeline facilitates passing the output of a command as input to another. Pipelines are a common mechanism for joining commands for example the Linux shell provides this feature. However, the PowerShell Pipeline is more advanced. Other pipeline implementations work primarily with text, while the PowerShell pipeline operates on .Net objects.

PowerShell Pipeline And Utility Cmdlets

As mentioned the PowerShell Pipeline operates on .Net objects. PowerShell provides a number of cmdlets that provide useful functionality and clue cmdlets together when working with the Pipeline. Some of these are listed below

PowerShell Where-Object Cmdlet

The PowerShell Where-Object cmdlet allows us to filter the objects passed through the Pipeline.

1
Get-Process | Where {$_.WorkingSet -gt 500mb} | Format-Table

Above we use the Where-Object Cmdlet to filter all processes that are using more than 500MB of memory. We then pipe this output to the Format-Table Cmdlet.

1
2
3
4
5
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName          
-------  ------    -----      ----- -----   ------     -- -----------          
  1758     195   490472     604620  1101 2,821.87   5788 devenv
  1406     259  1237480    1284208  1917 3,021.05   7600 firefox
   670      20  1236500     758556  1292            7624 mysqld

PowerShell Select-Object Cmdlet

The PowerShell Select-Object cmdlet allows us to filter what properties of the object are passed through the Pipeline. The Select-object cmdlet can also be used to select a number of objects from a list.

1
Get-Process | Where {$_.WorkingSet -gt 500mb} | Select Id, ProcessName, WS | Format-Table -    AutoSize

Above, again we use the Where-Object Cmdlet to filter all processes that are using more than 500MB of memory. We then use the Select-Object cmdlet to select the properties that we are interested in. Finally, the output is piped to the Format-Table Cmdlet with the AutosSize configuration parameter. The AutoSize parameter will fix the formatting of the displayed content in the terminal.

1
2
3
4
5
 Id ProcessName         WS
 -- -----------         --
5788 devenv       619159552
7600 firefox     1323311104
7624 mysqld       776761344

PowerShell Sort-Object Cmdlet

The PowerShell Sort-Object cmdlet allows us to sort the objects passed over the PowerShell Pipeline. For example let’s improve on the last example by sorting by memory usage.

1
Get-Process | Where {$_.WorkingSet -gt 500mb} | Select Id, ProcessName, WS | Sort WS -    Descending | Format-Table -AutoSize

The above command uses the Sort-Object cmdlet to sort the data by memory usage.

1
2
3
4
5
Id   ProcessName         WS
 -- -----------         --
7600 firefox     1321885696
7624 mysqld       776761344
5788 devenv       619139072

Conclusion

In this tutorial we introduced Powershell Pipeline and looked at some example Cmdlets.