Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

1 Answer 1

up vote 4 down vote accepted

Foreach and Foreach-Object are 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
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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