Halt batch file until service stop is complete?

点点圈 提交于 2019-12-18 11:17:24

问题


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?


回答1:


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

See - NET stop




回答2:


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



回答3:


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




回答4:


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.




回答5:


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.




回答6:


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


来源:https://stackoverflow.com/questions/2874911/halt-batch-file-until-service-stop-is-complete

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