0

I have the following command which executes successfully on a remote Windows server.

Invoke-Command -ComputerName $ComputerName -UseSSL -SessionOption $sessionOptions -Credential $cred -ScriptBlock
 {Start-Service "Test Service"}

I am attempting to pass in the script block as a variable so that I can execute any arbitrary command on the particular server, but I can't seem to pass the ScriptBlock argument successfully. The code executes without any errors, but does not start the remote service.

$ScriptBlock = Start-Service "Test Service"

Invoke-Command -ComputerName $ComputerName -UseSSL -SessionOption $sessionOptions -Credential $cred -ScriptBlock
 {$args[0]} -ArgumentList $ScriptBlock

1 Answer 1

1

Enclose the code in {} to define a scriptblock literal when assigning it to your $ScriptBlock variable, then pass that as the argument to the -ScriptBlock parameter:

$ScriptBlock = { Start-Service "Test Service" }

Invoke-Command -ScriptBlock $ScriptBlock -ComputerName $ComputerName -UseSSL -SessionOption $sessionOptions -Credential $cred 
Sign up to request clarification or add additional context in comments.

1 Comment

That was it. Can't believe I overlooked that, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.