How to restart a Windows service from a script

windows-command-promptwindows-service

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?

Best Answer

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