The Fool
The Fool

Reputation: 20567

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

(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

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

Upvotes: 4

Views: 4124

Answers (2)

js2010
js2010

Reputation: 27606

Here's another way to do it, without waiting for the whole foreach to finish. It's like defining a function on the fly:

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

Also, you can pipe it directly:

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

Upvotes: 2

Maximilian Burszley
Maximilian Burszley

Reputation: 19694

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 ($file in Get-ChildItem -File) {
    # ...
}) | Format-List

This same pattern can be used for if and switch statements as well.

Upvotes: 3

Related Questions