powershellazure-powershell

Foreach parallel Missing an argument for parameter 'xxx'. Specify a parameter of type 'System.Object' and try again


i'm using a parallel foreach in a powershell script. I'm getting a problem to pass external variable inside the loop. The code is following

[CmdletBinding()]
param (
    $var1,
    $var2,
    $var3,
    $var4
)


$MyArr | ForEach-Object -Parallel {
 
   
      Invoke-Expression ".\myscript.ps1 -var1 $var1 -var2 $var2 -var3 $var3 -var4 $var4"


}

when I execute it, I'm getting:

myscript.ps1: Missing an argument for parameter 'var1'. Specify a parameter of type 'System.Object' and try again.

There is a way to fix it?


Solution

  • Use the using: special scope modifier to make PowerShell copy the values to the underlying runspace:

    $MyArr | ForEach-Object -Parallel {
        .\myscript.ps1 -var1 $using:var1 -var2 $using:var2 -var3 $using:var3 -var4 $using:var4
    }