I'm wondering how to work with nested Forach-Object, Where-Object and other Cmdlets in Powershell. For example this code:
$obj1 | Foreach-Object { $obj2 | Where-Object { $_ .... } }
So in the code block of Foreach-Object I use the elements of $obj1
as $_
. But the same happenn in the code block of Where-Object with $obj2
. So how can I access both objects elements in the Where-Object code block? I would have to do $_.Arg1 -eq $_.Arg1
but this makes no sense.
An important feature of foreach is the %:% operator. I call this the nesting operator because it is used to create nested foreach loops. Like the %do% and %dopar% operators, it is a binary operator, but it operates on two foreach objects.
The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.
In reality, foreach is an alias to the ForEach-Object cmdlet, and foreach (not the alias) is a statement. Each has its purpose.
The core difference here is where you use the command, one is used in the midst of a pipeline, while the other starts its own pipeline. In production style scripts, I'd recommend using the ForEach keyword instead of the cmdlet.
Another way do address this is with a slighty different foreach
ForEach($item in $obj1){ $obj | Where-Object{$_.arg -eq $item.arg} }
Still boils down to about_Scopes. $_
is always a reference to the current scope. As you must know ($_.Arg1 -eq $_.Arg1)
would just be refering to itself.
afaik, You'll need to keep a reference to the outer loop by putting it in a local variable.
$obj1 | Foreach-Object { $myobj1 = $_ $obj2 | Where-Object { $_ .... } }
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