Halt batch file until service stop is complete?

血红的双手。 提交于 2019-11-30 02:52:20
mdma

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

See - NET stop

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!