Difference between ForEach and ForEach-Object in powershell

They’re different commands for different purposes. The ForEach-Object cmdlet is used in the pipeline, and you use either $PSItem or $_ to refer to the current object in order to run a {scriptblock} like so:

1..5 | ForEach-Object {$_}

>1
>2
>3
>4
>5

Now, you can also use a very similiar looking keyword, ForEach, at the beginning of a line. In this case, you can run a {scriptblock} in which you define the variable name, like this:

ForEach ($number in 1..5){$number}
>1
>2
>3
>4
>5

The core difference here is where you use the command, one is used in the midst of a pipeline, while the other starts its own pipeline. In production style scripts, I’d recommend using the ForEach keyword instead of the cmdlet.

Leave a Comment