Variables in nested Foreach-Object and Where-Object

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 { $_ .... }
}

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.


If the match is simple enough, you can get rid of the inner code block and avoid a local variable.

$obj1 | Foreach-Object { 
    $obj2 | Where property -eq $_.property
}

e.g:

$array = ("zoom", "explorer", "notreal")
$array | foreach { get-process | where ProcessName -EQ $_ | Out-Host }

Tags:

Powershell