管道和 foreach 循环 [英] pipes and foreach loops

查看:32
本文介绍了管道和 foreach 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Recently, I've been playing with PowerShell, and I've noticed some weird behavior when using pipes and foreach loops that I couldn't understand.

这个简单的代码有效:

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

有道理.

但是这段代码不会:

foreach ($i in gci){$i.length} | measure -max

我收到以下错误:

An empty pipe element is not allowed.
At line:1 char:33
+ foreach ($i in gci){$i.length} | <<<<  measure -max
+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : EmptyPipeElement

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

What is the difference between those two methods, and why does the second one fails?

推荐答案

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

The foreach statement doesn't use the pipeline architecture, so its output cannot be passed to a pipeline directly (i.e. item by item). To be able to pass output from a foreach loop to a pipeline you must run the loop in a subexpression:

$(foreach ($item in Get-ChildItem) { $item.Length }) | ...

或先将其收集到变量中:

or collect it in a variable first:

$len = foreach ($item in Get-ChildItem) { ... }
$len | ...

如果要在管道中处理数据,请改用 ForEach-Object cmdlet:

If you want to process data in a pipeline use the ForEach-Object cmdlet instead:

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

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

For further explanation of the differences between foreach statement and ForEach-Object cmdlet see the Scripting Guy blog and the chapter on loops from Master-PowerShell.

这篇关于管道和 foreach 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆