How do I restart a Windows service from a script?
I have a batch script that looks like:
sc stop myservice
sc start myservice
it errors out because sc doesn't wait till the service is stopped. How do I restart a service with a script?
The poster wants to ensure the service is stopped before trying to restart it. You can use a loop on the output of "sc query" doing something like this:
:stop
sc stop myservice
rem cause a ~10 second sleep before checking the service state
ping 127.0.0.1 -n 10 -w 1000 > nul
sc query myservice | find /I "STATE" | find "STOPPED"
if errorlevel 1 goto :stop
goto :start
:start
net start | find /i "My Service">nul && goto :start
sc start myservice
May be missing something, but I use this all the time:
net stop "myservice"
net start "myservice"
or shorter:
net stop "myservice" && net start "myservice"
Dead simple with powershell:
PS >Restart-Service MySrvcHere
Even better, using display names:
PS >Restart-Service -displayname "My Service Name Here"
Get-Help Restart-Service
for more
If it is purely for restarting the service, you can use
Net stop myservice
Net start myservice
However, if you want access to the options of sc, you can use the start /wait command
start /B /WAIT CMD /C "sc stop myservice"
start /B /WAIT CMD /C "sc start myservice"
this technique is a more general solution that can be applied to any command.
To have quiet restart of some service, which asks confirmations to be stopped (as Server service, for example), You could add /y to the end of stop command.
net stop Server /y
net start Server
It would be helpful for automatic script execution.