9

I want to pass some arguments to a script block that will be run on a remote Sitecore instance via SPE remoting. I wrote this script as a test, but it's not working.

$session = New-ScriptSession -ConnectionUri "http://sc81up3" -Username admin -Password b
Invoke-RemoteScript -Session $session -ScriptBlock { param($name) Write-Output "hi $name" } -Arguments @{"name"="Ben"}
Stop-ScriptSession -Session $session

This wasn't my first attempt. I tried, just passing "Ben" as the Argument parameter, but that caused an error about not being able to convert a string to a hashtable. When I pass the hashtable as shown above, I don't get an error, but the output is just hi, so it seems the value isn't getting passed.

What is the correct way to pass arguments to the script block executed by Invoke-RemoteScript?

7

The SPE Gitbook provides some alternate examples using the $using:VARIABLE syntax.

Example: The following will pass the $data object into the scriptblock for remote execution.

Import-Module -Name SPE
$session = New-ScriptSession -Username michael -Password b -ConnectionUri https://spe.dev.local

$data = @{"name"="Michael"}
Invoke-RemoteScript -Session $session -ScriptBlock {
    Write-Output "Hi $(($using:data).name)"
}
Stop-ScriptSession -Session $session

Note: The current version of the remoting module requires you to wrap the $using:data in parenthesis if you want to directly access properties. Otherwise assign it to a variable first.

  • Ah, I quickly scanned through that looking for examples with the -Arguments parameter. I guess I was looking for the wrong thing. Is $using preferred over -Arguments? – Ben Golden Oct 29 '16 at 20:01
  • I prefer because it looks cleaner and requires less typing. Either are acceptable. – Michael West Oct 29 '16 at 20:04
  • If I try to pass an array with the $using syntax, only the first item makes it through. Do I need to do something special for arrays? – Ben Golden Oct 31 '16 at 14:53
  • Interesting observation. I'll investigate. – Michael West Oct 31 '16 at 15:05
  • 2
    For reference, this should be fixed in 4.2 or newer. – Michael West Nov 17 '16 at 2:27
5

I found an example in the comments included in the Invoke-RemoteScript.ps1 script file. Here is a modified version of my script that outputs hi Ben as expected:

$session = New-ScriptSession -ConnectionUri "http://sc81up3" -Username admin -Password b
Invoke-RemoteScript -Session $session -ScriptBlock { Write-Output "hi $($params.name)" } -Arguments @{"name"="Ben"}
Stop-ScriptSession -Session $session

The hashtable that you pass with -Arguments is accessible within the script as the properties on the $params variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.