我正在尝试了解 powershell 重定向的行为。
这 2 个 powershell 代码有不同的行为,但我不知道为什么。
此代码有效:
PS C:\Users\myHome> 'file1','file2' | foreach { echo $_ } > toto
PS C:\Users\myHome>
但是这段代码失败了:
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>
我希望两个 powershell 代码得到相同的结果。
为什么会有行为差异?
仅在管道中允许重定向,而
foreach
是一个以不同方式解析的语句。
您可以将其包装在子表达式中以使重定向起作用:
$(foreach ($file in 'file1','file2'){ echo $file }) > toto2
这对于您想要使用流控制语句结果的其他地方也是必要的,例如在管道的开头使用它们(非常类似于重定向),或者将结果分配给变量。
但就我个人而言,对于应该是管道的事情(其中对象被获取、过滤、投影等)我总是在 PowerShell 中使用管道,因为这是用语言表达此类事情的最自然的方式。