Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pipe output from foreach, in powershell

Tags:

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

like image 876
The Fool Avatar asked Sep 05 '25 03:09

The Fool


2 Answers

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.

like image 95
Maximilian Burszley Avatar answered Sep 09 '25 23:09

Maximilian Burszley


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
like image 34
js2010 Avatar answered Sep 09 '25 22:09

js2010