Dos - Wait for a service to completely stopped

By xngo on December 5, 2019

In MS Windows, you can stop a service by running either the following commands:

  • net.exe stop "Service name"
  • sc.exe stop "Service name"

However, both commands don't wait for the service to completely stopped before continuing. They simply issue a stop signal and them move on to the next command. Even with net.exe, it doesn't completely wait for the service to stop. It only wait for a certain threshold and then assume the service is stopped.

Here is a batch script that will issue a stop service signal and then wait for the service to be completely stopped before moving on to the next command. In order to use the script below, make sure to change the followings to match your situation:

  • Change SERVICE NAME to your service name.
  • Change COMPUTER NAME to your computer name(i.e. hostname) or use your IP address.
REM -- Change SERVICE NAME and COMPUTER NAME to your situation.
set service_name="SERVICE NAME"
set computer_name="COMPUTER NAME"

REM -- Stop service and wait until status is STOPPED.
sc \\%computer_name% stop %service_name%
:loop
sc \\%computer_name% query %service_name% | find "STOPPED"
if errorlevel 1 (
    timeout 1 /nobreak
    goto loop
)

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.