3

In PowerShell, foreach and % are default aliases to ForEach-Object. However, it seems the command behaves differently depending upon how it is called.

Particularly, I have a hard time getting the command to work without feeding it input from the pipeline, unless I'm specifically using the foreach alias.

enter image description here

Is there something I'm doing wrong here, or is this by design for some reason?

6

The foreach statement and the Foreach-Object Cmdlet NOT the same thing.

For one:

In the case of the Foreach-Object, the statement body is executed as soon as each object is produced. In the foreach statement, all the objects are collected before the loop body begins to execute. This has two implications

There are also performance and syntax differences.

$i = @(1..3) | ForEach-Object {Write-Host $_}

Does work in Foreach-Object.

  • That line of script works for foreach, ForEach-Object, and %. It can even be shortened to 1..3|%{$_}. :-) – Iszi Nov 13 '13 at 16:38
  • Oh geez, don't code-golf me! @Iszi I actually work hard to write out my commands most of the time ;) I like readable code commands. But very nice. – Austin T French Nov 13 '13 at 16:43
  • 3
    Why use foreach vs foreach-object? - "First it is important to understand that foreach -ne foreach-object unless used in the pipeline." – Ƭᴇcʜιᴇ007 Nov 13 '13 at 16:53
  • It looks like if we want to use ForEach-Object without piping, with syntax somewhat similar to foreach we can do ForEach-Object -InputObject (1..3) {$_} or % -i(1..3){$_}. – Iszi Nov 13 '13 at 18:01
  • 1
    might be good to clarify in the first sentence "The foreach statement and the Foreach-Object Cmdlet are not..." - for someone who doesn't already know the answer, I think it would be helpful to further distinguish the two at first sight (?) anyone else wanna weigh in on this? – Code Jockey Aug 7 '15 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.