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
It does not work because when the scriptblock is executed on the remote server, the variable
$myvaldoes not exist in session state; it only exists on the local (client) side. The powershell v2/v3 compatible way to do this is:Another powershell v3 (only) way is like this:
The
$usingprefix 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.)