md1
md1

Reputation: 15

Invoke-Command error

I have the following Powershell script

$se1 = New-Pssession  -computerName .
$service = "Myservice"  
Invoke-Command -session $se1 -scriptblock { Stop-Service -displayname  $service   } 
Remove-PSSession  $se1 

It fails with the error

Cannot bind argument to parameter 'DisplayName' because it is null

It seems to be the value of $service is passed when the cmdlet is executed.

Any hints to resolve it ?

Thanks

Upvotes: 1

Views: 944

Answers (1)

mjolinor
mjolinor

Reputation: 68243

You need to pass an argument to the script block. It won't expand variables in the script block until it's executed at the remote system, and that local variable doesn't exist there.

$se1 = New-Pssession  -computerName .
$service = "Myservice"  
Invoke-Command -session $se1 -scriptblock { Stop-Service -displayname  $args[0]  }  -argumentlist $service
Remove-PSSession  $se1 

The argument list will get passed to the remote system along with the script block.

Upvotes: 1

Related Questions