简体   繁体   English

如何从 foreach 到 powershell

[英]How to pipe output from foreach, in powershell

I am trying to pipe the output from a foreach loop into a format command but it does not work.我正在尝试将 pipe 和 output 从foreach循环转换为格式命令,但它不起作用。 The reason I think is possible is because this works.我认为可能的原因是因为这行得通。

$op = foreach ($file in (Get-ChildItem -File)) {
    $file |
    Get-Member |
    Where-Object {$_.MemberType -eq "Method" -and $_.Definition -like "*system*" } |
    Select-Object -Property Name, MemberType
}

$op | Format-List

If I can assign the whole output to a variable, and pipe the variable into another command, why does the following NOT work?如果我可以将整个 output 分配给一个变量,并将 pipe 变量分配给另一个命令,为什么以下不起作用?

(foreach ($file in (Get-ChildItem -File)) {
    $file |
    Get-Member |
    Where-Object {$_.MemberType -eq "Method" -and $_.Definition -like "*system*" } |
    Select-Object -Property Name, MemberType
}) | Format-List

Of course I tried without parents, but ultimately I think if anything, the parents make sense.当然我试过没有父母,但最终我认为如果有的话,父母是有道理的。 It is like $file in (Get-ChildItem -File) where it evaluates the expression in the parents and uses the result as the actual object它就像$file in (Get-ChildItem -File)它在其中评估父项中的表达式并将结果用作实际的 object

Is there a way to make this work?有没有办法使这项工作?

please note that the code is not supposed to achieve anything (else) than giving an example of the mechanics请注意,代码不应该实现任何东西(其他),而不是给出一个机制的例子

foreach does not have an output you can capture (besides the sugar you've found with variable assignment), but you can gather all the objects returned by wrapping it in a subexpression: foreach没有可以捕获的 output (除了通过变量赋值找到的糖),但是您可以通过将其包装在子表达式中来收集所有返回的对象:

$(foreach ($file in Get-ChildItem -File) {
    # ...
}) | Format-List

This same pattern can be used for if and switch statements as well.同样的模式也可以用于ifswitch语句。

Here's another way to do it, without waiting for the whole foreach to finish.这是另一种方法,无需等待整个 foreach 完成。 It's like defining a function on the fly:这就像在运行中定义 function :

& { foreach ($file in Get-ChildItem -File) {
      $file |
      Get-Member |
      Where-Object {$_.MemberType -eq "Method" -and $_.Definition -like "*system*" } |
      Select-Object -Property Name, MemberType
    } 
} | format-list

By the way, $( ) can go anywhere ( ) can go, but it can enclose multiple statements separated by newlines or semicolons.顺便说一句, $( )可以在任何地方 go ( )可以在 go 中,但它可以包含多个语句,用换行符或分号分隔。

Also, you can pipe it directly:另外,您可以直接 pipe 它:

Get-ChildItem -File |
Get-Member |
Where-Object {$_.MemberType -eq "Method" -and $_.Definition -like "*system*" } |
Select-Object -Property Name, MemberType | 
Format-List

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM