1

I have very simple powershell script that starts service remotely.

Invoke-Command -Session $session -ScriptBlock { Start-Service "My test service v1" }

works fine but

$myval="My test service v1"
Invoke-Command -Session $session -ScriptBlock { Start-Service $myval }

fails with

Cannot validate argument on parameter 'InputObject'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again. + CategoryInfo : InvalidData: (:) [Start-Service], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StartServiceCommand + PSComputerName : mdfiletest

To me they are the same. Why is this not working? thanks

user156144
  • 2,215
  • 4
  • 29
  • 40

1 Answers1

3

It does not work because when the scriptblock is executed on the remote server, the variable $myval does not exist in session state; it only exists on the local (client) side. The powershell v2/v3 compatible way to do this is:

invoke-command -session $session -scriptblock {
      param($val); start-service $val } -args $myval

Another powershell v3 (only) way is like this:

invoke-command -session $session -scriptblock { start-service $using:myval }

The $using prefix is a special pseudo-scope which will capture the local variable and try to serialize it and send it remotely. Strings are always serializable (remotable.)

x0n
  • 51,312
  • 7
  • 89
  • 111