Reputation: 475
Why can't I pipe the result from a foreach-object operation to another foreach-object operation? I can't get the last ForEach-Object loop to run. It outputs nothing.
$mailboxstatistics |
Select-Object -First 20 |
Where { $_.FolderPath.Contains("/Inkorg") -eq $True } |
ForEach-Object -Begin{
Write-Host "Begin"
} -Process{
#Write-Host "Process"
Write-Host $($_.FolderPath)
} -End{
Write-Host "End"
} |
ForEach-Object{
Write-Host "test"
}
Upvotes: 1
Views: 5575
Reputation: 36
Editing my original answer: You are asking "WHY does the pipeline not let you pipe from one ForEach to another ForEach," as opposed to a practical solution. This requires a basic definition of what the pipeline does. From
The pipeline in PowerShell passes .NET framework objects as opposed to other types of shells which may pass text. So, based off the definition above, what are you expecting the For-EachObject to output to be the input from pipeline for the next sequence? When you're doing a Where-Object or Select-Object, you're refining the collection. You've already stated that the objects are sent to Write-Host. There would not be anything in the pipeline as an output after the ForEach finishes.
I'm not sure the advantage to the daisy chain of pipelining. I could be wrong about this, I generally break sequences with variables. The ForEach will consume and operate on every single item of the collection piped in, and then produce or pipe out what exactly, to the next in the piping chain? I understand ForEach can accept pipeline input as a collection of objects, such as an array. So I see advantages to its use of only iterating through the number of items, as opposed to the classic
for($i = 0; $i-lt $collectionOfOjbects.Length; $i++)
{
Verb-Noun $collectionOfObjects[$i]
}
Is it possible to try the selecting/sorting refining first, then pipe that to the ForEach iterations?
$myFirst20MailboxStatsInkorg = $mailboxstatistics | Select-Object -First 20 | Where { $_.FolderPath.Contains("/Inkorg") -eq $True }
#first round of iteration:
$myFirst20MailboxStatsInkorg | ForEach-Object -Begin{
Write-Host "Begin"
} -Process{
#Write-Host "Process"
Write-Host $($_.FolderPath)
} -End{
Write-Host "End"
}
#second round of iteration
$myFirst20MailboxStatsInkorg | ForEach-Object{
Write-Host "test"
}
Upvotes: 2