Pass arguments to a scriptblock in powershell

dexter picture dexter · May 2, 2013 · Viewed 97.2k times · Source

I guess you can't just do this:

  $servicePath = $args[0]

  if(Test-Path -path $servicePath) <-- does not throw in here

  $block = {

        write-host $servicePath -foreground "magenta"

        if((Test-Path -path $servicePath)) { <-- throws here.

              dowork 
        }
  }

So how can I pass my variables to the scriptblock $block?

Answer

Lars Truijens picture Lars Truijens · May 3, 2013

Keith's answer also works for Invoke-Command, with the limit that you can't use named parameters. The arguments should be set using the -ArgumentList parameter and should be comma separated.

$sb = {
    param($p1,$p2)
    $OFS=','
    "p1 is $p1, p2 is $p2, rest of args: $args"
}
Invoke-Command $sb -ArgumentList 1,2,3,4

Also see here and here.