Emanuele
Emanuele

Reputation: 359

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?

Upvotes: 4

Views: 2067

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

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
}

Upvotes: 3

Related Questions