Home > OS >  Invoke-command with sending scriptblock param
Invoke-command with sending scriptblock param

Time:12-04

I have a script block

$test = {
param(
$path )
other stuff here...}

I assume I need to use Invoke-Command -ScriptBlock $test but how do I pass what the $path param should be ?

CodePudding user response:

You can pass the value for the $path parameter when using Invoke-Command by using the -ArgumentList parameter and providing a list of the values for the parameters in the script block, in the correct order. For example, if you want to pass the value C:\test for the $path parameter in the script block above, you could use the following command:

Invoke-Command -ScriptBlock $test -ArgumentList C:\test

This would pass the value C:\test as the value for the $path parameter in the script block, which you can then use in your script.

Note that you may need to enclose the value for the $path parameter in quotes if it contains spaces or other special characters. For example, if the value for the $path parameter was C:\my test folder, you would need to use the following command instead:

Invoke-Command -ScriptBlock $test -ArgumentList "C:\my test folder"

CodePudding user response:

To invoke script blocks with parameters (locally, in the context of the current user):

$test = { 
  param($path)
  "[$path]" # diagnostic output.
}

# Note: 
#  * Target parameter -path is *positionally implied*
#  * To be explicit, call: & $test -path 'my -path value' 
& $test 'my -path value' 
  • Related