When I run the following command:
Set-Service -ComputerName appserver -Name MyService -Status Stopped
I get an error message:
Set-Service : Cannot stop service 'My Service (MyService)' because it is
dependent on other services.
At line:1 char:12
+ Set-Service <<<< -ComputerName appserver -Name MyService -Status Stopped
+ CategoryInfo : InvalidOperation: (System.ServiceProcess.ServiceController:ServiceController) [Set-Service], ServiceCommandException
+ FullyQualifiedErrorId : ServiceIsDependentOnNoForce,Microsoft.PowerShell.Commands.SetServiceCommand
I can stop the service from the services.msc
GUI, and I can start the service with Set-Service
, but I can't stop it again.
It is true that the service depends on some other services, but I don't understand why that would prevent me from stopping it—nothing else depends on it.
The Set-Service
cmdlet is for changing the configuration of a service. That you can use it to stop a service by changing its status is just coincidental. Use the Stop-Service
cmdlet for stopping services. It allows you to stop dependent services as well via the parameter -Force
. You'll need to retrieve the service object with Get-Service
first, though, since Stop-Service
doesn't have a parameter -ComputerName
.
Get-Service -Computer appserver -Name MyService | Stop-Service -Force
I eventually resolved this problem with the following code, which calls sc
to stop the service and then waits for it to finish stopping. This achieves the same result as expected from Set-Service -Status Stopped
; that is, when it returns the service has been stopped. (sc
on its own starts to stop the service, but does not wait until it has finished stopping.)
Start-Process "$env:WINDIR\system32\sc.exe" \\APPSERVER,stop,MyService -NoNewWindow -Wait
while ((Get-Service -ComputerName APPSERVER -Name MyService |
Select -ExpandProperty Status) -ne 'Stopped') {
Write-Host "Waiting for service to stop..."
Start-Sleep -Seconds 10
}