Powershell 管道和foreach回路

Powershell 管道和foreach回路,powershell,powershell-2.0,Powershell,Powershell 2.0,最近,我一直在玩PowerShell,我注意到在使用管道和foreach循环时出现了一些我无法理解的奇怪行为 这个简单的代码可以工作: $x = foreach ($i in gci){$i.length} $x | measure -max 有道理 但该代码不会: foreach ($i in gci){$i.length} | measure -max 我得到了以下错误: 不允许使用空管道元素。 第1行字符:33 +foreach($i在gci中){$i.length}在管道化生成的对象

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

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

$x = foreach ($i in gci){$i.length}
$x | measure -max
有道理

但该代码不会:

foreach ($i in gci){$i.length} | measure -max
我得到了以下错误:

不允许使用空管道元素。
第1行字符:33

+foreach($i在gci中){$i.length}在管道化生成的对象之前,您需要像在第一次测试中那样评估
foreach

$(foreach ($i in gci){$i.length}) | measure -max
或者,也可以使用
%
速记,在配管之前对其进行评估:

gci | % { $_.Length } | measure -max

foreach
语句不使用管道体系结构,因此其输出不能直接传递到管道(即逐项传递)。要能够将输出从
foreach
循环传递到管道,必须在子表达式中运行循环:

$(foreach ($item in Get-ChildItem) { $item.Length }) | ...
或者先将其收集到变量中:

$len = foreach ($item in Get-ChildItem) { ... }
$len | ...
如果要处理管道中的数据,请改用
ForEach对象
cmdlet:

Get-ChildItem | ForEach-Object { $_.Length } | ...

有关
foreach
语句和
foreach对象
cmdlet之间差异的进一步解释,请参阅和来自主PowerShell的。

公平地说。%是foreach对象cmdlet的缩写,与问题中使用的foreach循环不同。:-)