Difference between piping commands and using Foreach-Object

Hi everyone!
Couldnt find this question surfing the Internet. Only foreach\foreach-object comparison.

Let’s take two examples:

  1. Get-Process -name msedge,putty | Stop-Process
  2. Get-Process -name msedge,putty | Foreach-Object {Stop-Process $_}

The both are doing the same operation. What about the method in each one? Am I right If it’s also the same supposing the first example just omits the “Foreach-Object” construction and let the code looks more readable/aesthetic?

Hi, welcome to the forum :wave:

PowerShell In a Month of Lunches calls your first example the PowerShell or command-oriented approach and your second example ‘the scripting approach’.

The point here is that using ForEach is often (but not always) an indicator that you’re taking a scripting approach rather than a pure PowerShell approach […] There are only two times when I find myself legitimately using ForEach:

  • When there’s no cmdlet capable of doing what I need to a bunch of objects at once. This most often happens when I need to execute a method against a bunch of objects, and there isn’t a cmdlet that can perform the equivalent task.
  • When I need to manually ‘unwind’ a bunch of objects and send them off, one at a time, to a custom function that I’ve written, which can only work with one at a time.

Source: Learn Windows PowerShell in a Month of Lunches by Don Jones, p 226.

Bear in mind, for your example, you don’t actually need the pipeline at all:

Stop-Process -Name msedge,putty
3 Likes

I’ve run into similar issues in the past, and like the explanation found here:

It is a bit lengthy, but the author goes through each step of why ForEach-Object is slower. Taught me something about the performance hit caused by the parameter binder in ForEach-Object, as well as the difference between how this block handles iterating through objects (creating an internal pipeline and thus repeating the entire code each time) vs how the pipe itself handles it. Happy reading :slight_smile:

3 Likes

Thanks for pointing out to the bad example. Anyway the meaning is clear

Thanks for your reply. The article looks interesting, I’ll take a note to read it.
Also I got a detailed answer here https://stackoverflow.com/questions/68269106/powershell-difference-between-piping-commands-and-using-foreach-object/68272102#68272102