Preston Martin
Preston Martin

Reputation: 2963

Powershell Invoke-Command with arbitrary ScriptBlock

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

Upvotes: 0

Views: 541

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174475

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 

Upvotes: 1

Related Questions