2

I'm trying to stop a remote service using this Powershell script:

$hostname1 = "myhost"
$serviceName = "myservice"
Write-Host "Hostname: $hostname1"
Write-Host "Service name: $serviceName"
Invoke-Command -ComputerName $hostname1 -ScriptBlock {
  Stop-Service -Name $serviceName -Force
}

But getting this error message:

Cannot bind argument to parameter 'Name' because it is null.
    + CategoryInfo          : InvalidData: (:) [Stop-Service], ParameterBindin
   gValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,M icrosoft.PowerShell.Commands.StopServiceCommand

If I remove Invoke-Command from the script, I can see the variables are initialized correctly:

$hostname1 = "myhost"
$serviceName = "myservice"
Write-Host "Hostname: $hostname1"
Write-Host "Service name: $serviceName"

Returns:

Hostname: myhost
Service name: myservice

What can be a reason for this?

Thanks, Roman

Roman
  • 1,278
  • 2
  • 12
  • 14
  • 1
    Possible duplicate of [How do I pass variables with the Invoke-Command cmdlet?](http://stackoverflow.com/questions/36328690/how-do-i-pass-variables-with-the-invoke-command-cmdlet) – user4003407 Oct 26 '16 at 22:24
  • http://stackoverflow.com/questions/36339616/ and http://stackoverflow.com/questions/13036327/ and http://stackoverflow.com/questions/37858282/ – TessellatingHeckler Oct 26 '16 at 22:31
  • Thanks a lot! Was stuck and as soon I posted my question I found an answer myself. – Roman Oct 26 '16 at 22:33

2 Answers2

4

A little bit of further digging and I found the answer myself - need to use -argumentlist

$hostname1 = "myhost"
$serviceName = "myservice"
Write-Host "Hostname: $hostname1"
Write-Host "Service name: $serviceName"
Invoke-Command -ComputerName $hostname1 -ScriptBlock {
  Stop-Service -Name $args[0] -Force
} -argumentlist $serviceName
Roman
  • 1,278
  • 2
  • 12
  • 14
0

Another Solution
Please use the automatic variable '$using'.

$hostname1 = "myhost"
$serviceName = "myservice"
Write-Host "Hostname: $hostname1"
Write-Host "Service name: $serviceName"
Invoke-Command -ComputerName $hostname1 -ScriptBlock {
  Stop-Service -Name $Using:ServiceName -Force
} 
Jaimil Patel
  • 1,301
  • 6
  • 13