3

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

3

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

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
} 

Comments

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.