Question

I'm using a batch file to stop a Windows service. I'm using the sc command, but I'm open to other ideas, given the question below. The problem is that the batch file proceeds while the service is stopping (the stop argument to sc seems only to request the stop -- it doesn't wait for the stop).

How can I modify the batch file to not proceed until the stop is complete?

Was it helpful?

Solution

Use can use NET stop, which is synchronous, i.e it will wait until the service stops.

See - NET stop

OTHER TIPS

sc stop webdriveservice
:loop
sc query webdriveservice | find "STOPPED"
if errorlevel 1 (
  timeout 1
  goto loop
)

As mentioned above, NET STOP will send a stop command to the service, but, if the service takes more than a certain time (20 seconds or so is my observation), NET STOP will NOT wait for the service to actually stop before returning.

To actually pause the batch file until the service stops, you need to use an approach like those outlined in these threads:

How to check if a service is running via batch file and start it, if it is not running?

Stopping/Starting a remote Windows service and waiting for it to open/close

I believe net stop [Service] should wait until the service has fully stopped before moving on. sc stop [Service] simply sends a "stop" message to the service.

This is a bit crude but it worked for me in order to ensure that I could schedule a daily batch file to essentially RESTART a service.

NET STOP [Service]

:TryAgain

TIMEOUT /T 10 /NOBREAK

NET START [Service]

IF %ERRORLEVEL% NEQ 0 GOTO TryAgain

I realize with this code snippet that this could result in an endless loop if the service was to not successfully start. I just wanted to basically show how to get around the issue using TIMEOUT where a service may take longer to stop than what the NET STOP command allows.

Use the && symbol between commands. The && symbol waits to finish the previous command before proceed to next command.

All commands must be at the same command row. You can use as many commands you want in a row.

You can use also the pause command. With this, asks to press any key, before proceed to next procedure.

For example:

sc qdescription "MyServiceName" && echo. && sc stop "MyServiceName" && echo. && echo          [ "MyServiceName" service stopped ] && echo. && pause
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top