pipes and foreach loops

风格不统一 提交于 2019-11-29 16:48:54

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 | ...

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

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

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.

You need to evaluate the foreach before piping the resulting Object like you did in the first test:

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

Alternatively, use the % shorthand to which will evaluate it before piping it as well:

gci | % { $_.Length } | measure -max
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!