pipes and foreach loops

Question:

Recently, I’ve been playing with PowerShell, and I’ve noticed some weird behavior when using pipes and foreach loops that I couldn’t understand.

This simple code works:

Makes sense.

But this code won’t:

And I’m getting the following error:

What is the difference between those two methods, and why does the second one fails?

Answer:

The foreach statement doesn’t use the pipeline architecture, so its output cannot be passed to a pipeline directly (i.e. item by item). To be able to pass output from a foreach loop to a pipeline you must run the loop in a subexpression:

or collect it in a variable first:

If you want to process data in a pipeline use the ForEach-Object cmdlet instead:

For further explanation of the differences between foreach statement and ForEach-Object cmdlet see the Scripting Guy blog and the chapter on loops from Master-PowerShell.

Source:

pipes and foreach loops by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply