管道和 foreach 循环

Jel*_*ean 10 powershell powershell-2.0

最近,我一直在使用 PowerShell,我注意到在使用管道和foreach循环时出现了一些我无法理解的奇怪行为。

这个简单的代码可以工作:

$x = foreach ($i in gci){$i.length}
$x | measure -max
Run Code Online (Sandbox Code Playgroud)

说得通。

但这段代码不会:

foreach ($i in gci){$i.length} | measure -max
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

$x = foreach ($i in gci){$i.length}
$x | measure -max
Run Code Online (Sandbox Code Playgroud)

这两种方法有什么区别,为什么第二种方法会失败?

Ans*_*ers 13

foreach语句不使用管道架构,因此它的输出不能直接传递到管道(即逐项)。为了能够将foreach循环的输出传递到管道,您必须在子表达式中运行循环:

$(foreach ($item in Get-ChildItem) { $item.Length }) | ...
Run Code Online (Sandbox Code Playgroud)

或者先将其收集到变量中:

$len = foreach ($item in Get-ChildItem) { ... }
$len | ...
Run Code Online (Sandbox Code Playgroud)

如果您想处理管道中的数据,请改用ForEach-Objectcmdlet:

Get-ChildItem | ForEach-Object { $_.Length } | ...
Run Code Online (Sandbox Code Playgroud)

foreach有关语句和ForEach-Objectcmdlet之间差异的进一步说明,请参阅脚本专家博客和有关 Master-PowerShell循环的章节。