How Pipeline Cmdlets Map to ForEach-Object

by Dec 15, 2015

There are a number of routine pipeline cmdlets like Where-Object and Select-Object, yet the only essential cmdlet is ForEach-Object. All the other pipeline cmdlets are just predefined implementations. Which is good because it saves code. Yet, to understand how they work, it might be useful to see how they map to ForEach-Object:

# Measure-Object
Get-Service |
  ForEach-Object -Begin { $i = 0} -Process { $i++ } -End { $i }

# Where-Object { $_.Status -eq 'Running' }
Get-Service |
  ForEach-Object -Process { if ($_.Status -eq 'Running') { $_ } }

# Select-Object -ExpandProperty DisplayName
Get-Service |
  ForEach-Object -Process { $_.DisplayName }

Obviously, these examples are not complete, nor should they encourage you to always use ForEach-Object. They simply should inspire you to better understand the streaming nature of the PowerShell pipeline, and how ForEach-Object is the core element of it.Once you know how to translate a pipeline cmdlet to ForEach-Object, you will also be able to turn your pipeline into a new command. We'll show you tomorrow why this can be pretty useful.

Twitter This Tip! ReTweet this Tip!