How to use PSCustomObject in PowerShell foreach parallel loop?

PowerShellMicrosoft TechnologiesSoftware & Coding

To use the PSCustomObject inside the Foreach Parallel loop, we first need to consider how we are using the variables inside the loop.

$Out = "PowerShell"
ForEach-Object -Parallel{
   Write-Output "Hello.... $($using:Out)"
}

So let see if we can store or change a value in the $out variable.

Example

$Out = @()
ForEach-Object -Parallel{
   $using:out = "Azure"
   Write-Output "Hello....$($using:out) "
}

Output

Line |
   4 | $using:out = "Azure"
     | ~~~~~~~~~~
     | The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept
     | assignments, such as a variable or a property.

The error says that the expression is invalid so we can’t manipulate the variable directly. So we have another method that we can use a temporary variable for it.

$Out = @()
ForEach-Object -Parallel{
   $dict = $using:out
   $dict = "Azure"
   Write-Output "Hello....$dict"
}

Similarly, we can use the PSCustomObject using the Temporary variable as shown below.

Example

$Out = @()
$vms = "Testvm1","Testvm2","Testvm3"
$vmout = $vms | ForEach-Object -Parallel{
   $dict = $using:out
   $dict += [PSCustomObject]@{
      VMName = $_
      Location = 'EastUS'
   }
   return $dict
}
Write-Output "VM Output"
$vmout

Output

VMName Location
------ --------
Testvm1 EastUS
Testvm2 EastUS
Testvm3 EastUS
raja
Published on 04-Jan-2021 10:03:17
Advertisements