PowerShell – Implicit foreach in PSv3 and the impact in execution time

Just now I’ve read a PowerTip from PowerShell.com about Implicit ForEach in PowerShell v3.

Although this makes for easier scripting, it’s also a lot slower! Let’s take the example from the PowerTip post…

Task: Close the window of notepad.exe

The ‘old’ way of doing this would simply by using the pipeline and the foreach-object cmdlet, like so:


And now when we use the implicit way you’ll notice that the foreach statement isn’t used anymore. Instead you’ll get all processes with the name ‘notepad’ and close their window…


Now isn’t that a neat and easy trick? But…

As you can see, using the implicit way makes your script slower.
Now, these are only milliseconds, right? Well, that’s totally true… but don’t forget that in this example it’s a 19 times increase in execution time when you use the implicit way… 19 times!!!

And now think about one of your larger scripts and imagine what the difference in execution time would be Knipogende emoticon


  1. jsnover says:

    It would be interesting to see what the difference is with a larger sample size. With small examples, it is very easy to get distorted values due to sampling errors (e.g. an ill-timed GC would throw things WAY off).

    The big difference here is that one streams and the other doesn’t. When you use parenthesis, it evaluates the entire expression and puts it into an array. THEN it does the operator. The pipeline streams. Again for small sample sizes, the delta should not be great but for large collections, it can add up.

    Jeffrey Snover [MSFT]
    Distinguished Engineer and Lead Architect for Windows Server

  2. Jeff Wouters says:

    I’ll make a post out of that, nice to investigate a bit further 🙂 No estimate on publish date though, a little swamped with projects and writing at the moment 🙁

Leave a Reply

Your email address will not be published. Required fields are marked *