I'm trying to understand the behaviour of the powershell redirections.
These 2 powershell code have different behaviour but I don't know why.
This code works :
PS C:\Users\myHome> 'file1','file2' | foreach { echo $_ } > toto
PS C:\Users\myHome>
But this code fails :
PS C:\Users\myHome> foreach ($file in 'file1','file2'){ echo $file } > toto2
file1
file2
> : The term '>' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:50
+ foreach ($file in 'file1','file2'){ echo $file } > toto2
+ ~
+ CategoryInfo : ObjectNotFound: (>:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\Users\myHome>
I expect the same result for both powershell code.
Why the behaviour difference ?
Redirection is only allowed in pipelines, whereas foreach
is a statement that's parsed differently.
You can wrap it in a subexpression to make redirection work:
$(foreach ($file in 'file1','file2'){ echo $file }) > toto2
This is also necessary for other places where you'd want to use the result of flow-control statements, such as using them at the start of a pipeline (very similar to redirection), or assigning the result to a variable.
But personally, for things that should be a pipeline (where objects are fetched, filtered, projected, etc.) I'd always use a pipeline in PowerShell, simply because it's the most natural way of expressing such things in the language.