How to use a variable inside a Foreach-Object Parallel?

PowerShellMicrosoft TechnologiesSoftware & Coding

There are two different types of the variable we can use inside foreach parallel loop. One that is declared inside and the other that is declared outside of the foreach parallel loop.

Please note − We are discussing here Foreach-Object Parallel loop, featured in PowerShell version 7. For a normal foreach loop inside and outside variables are the same.

Variable declared inside the Foreach parallel loop can be used directly with its name. For example,

Example

$vms = "TestVm1","TestVM2","TestVm3"
$Vms | ForEach-Object -Parallel{
   $var1 = $_
   Write-Output "Testing VM: $var1"
}

Output

Testing VM: TestVm1
Testing VM: TestVM2
Testing VM: TestVm3

In the above example, $var1 is declared inside the foreach parallel loop and we can use it directly by its name as shown. But the below example, $log variable declared outside the foreach parallel loop we can use it inside the loop with $Using keyword followed by the variable name.

$vms = "TestVm1","TestVM2","TestVm3"
$log = "Application"
$Vms | ForEach-Object -Parallel{
   $var1 = $_
   Write-Output "Checking $($using:log) on $var1"
}

Output

Checking Application on TestVm1
Checking Application on TestVM2
Checking Application on TestVm3

In the above example, $using:log variable is used inside the foreach parallel loop is a $log variable.

raja
Published on 04-Jan-2021 09:56:55
Advertisements