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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With