3

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 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?

REgards Thanks

aynber
  • 22,380
  • 8
  • 50
  • 63
Emanuele
  • 193
  • 2
  • 13
  • As an aside: [`Invoke-Expression` (`iex`) should generally be avoided](https://stackoverflow.com/a/51252636/45375); definitely [don't use it to invoke an external program or PowerShell script](https://stackoverflow.com/a/57966347/45375). – mklement0 Sep 30 '22 at 15:23

1 Answers1

2

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
}
mklement0
  • 382,024
  • 64
  • 607
  • 775
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • thanks for the advice. I modified it but i'm getting this error now: Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name. i put $using:var1 as your advice – Emanuele Sep 30 '22 at 15:03
  • @Emanuele The error indicates that something else is immediately following `:`, make sure you didn't include any whitespace eg. `$using: var1` - it has to be `$using:var1` or `${using:var1}` exactly – Mathias R. Jessen Sep 30 '22 at 15:07
  • Thanks, i think i miss something. Now foreach run but i think that the variable that i pass to the other script are empty. Seems that $using is not working and vars are empty – Emanuele Sep 30 '22 at 15:27
  • @Emanuele you might be able to splat on `$PSBoundParameters` just sayin :) – Santiago Squarzon Sep 30 '22 at 15:28
  • @SantiagoSquarzon `$PSBoundParameters` inside the loop body will have been overwritten – Mathias R. Jessen Sep 30 '22 at 15:38
  • sorry guys i never user $PSBoundParameters , can you please make an example? Just to understand – Emanuele Sep 30 '22 at 16:06
  • Hi all, was my mistake. I solved this morning. Thanks – Emanuele Oct 03 '22 at 10:33