Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables in nested Foreach-Object and Where-Object

Tags:

powershell

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.

like image 921
Michael Avatar asked Nov 03 '14 13:11

Michael


People also ask

Can ForEach loops be nested?

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.

What does the $_ mean in PowerShell?

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.

Is an alias for ForEach-Object True or false?

In reality, foreach is an alias to the ForEach-Object cmdlet, and foreach (not the alias) is a statement. Each has its purpose.

What is the difference in the ForEach-Object cmdlet and the ForEach scripting construct?

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.


2 Answers

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.

like image 37
Matt Avatar answered Sep 19 '22 11:09

Matt


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 { $_ .... } } 
like image 199
Lieven Keersmaekers Avatar answered Sep 20 '22 11:09

Lieven Keersmaekers