Halt batch file until service stop is complete?

后端 未结 7 1151
南笙
南笙 2020-12-25 10:40

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

相关标签:
7条回答
  • 2020-12-25 11:16
    sc stop webdriveservice
    :loop
    sc query webdriveservice | find "STOPPED"
    if errorlevel 1 (
      timeout 1
      goto loop
    )
    
    0 讨论(0)
  • 2020-12-25 11:16

    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

    0 讨论(0)
  • 2020-12-25 11:18

    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.

    0 讨论(0)
  • 2020-12-25 11:19

    I had a similar issue with net stop. It returns when the service is indeed stopped, but the executable may still be running.
    For upgrade reasons, this is not good enough, we need to wait until the process has finished.

    I've used a simple loop to wait until the service executable has actually finished:

    net stop "ServiceName"
    :loop1
    set _CmdResult=""
    for /f "tokens=1" %%a in ('TASKLIST ^| FINDSTR ServiceName.exe') do set _CmdResult=%%a
    if not %_CmdResult% == ""  (
      timeout 5
      goto loop1
    )
    

    Once the the executable finishes, the loop will break.

    0 讨论(0)
  • 2020-12-25 11:23

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

    See - NET stop

    0 讨论(0)
  • 2020-12-25 11:26

    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.

    0 讨论(0)
提交回复
热议问题