Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 5 down vote accepted

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.

share|improve this answer
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. – AthomSfere Nov 13 '13 at 16:43
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
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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .