Video: FAQ PowerShell - Foreach vs Foreach-Object

4/26/2018 3355 Contributors

Here is a basic overview of the difference between Foreach and Foreach-Object:

Foreach-Object works at the pipeline and processes each object one at a time. The variable you use to access the object in the pipeline is $_ or $PSItem (If you use PowerShell V3+) You also have the ability to add Begin and End scriptblocks to run commands before and after you process each object in the pipeline.

Foreach loads all objects of a collection into memory at once and then processes them.

Note: I didn't call out that Foreach-Object itself has an alias called foreach that can be used while in the pipeline. But alas, I did not remember that until after the video was published.