Dos - Restart a serivce remotely

By xngo on December 4, 2019

In MS Windows, you can use the command-line utility, sc.exe, that can be used to control a service locally or remotely. This utility is provided as part of the Windows SDK.

sc.exe doesn't have the restart option. Therefore, you have to stop and then start the service.

Here are the steps to remotely restart a service.

  1. Open command prompt as Run as administrator.
  2. To stop a service run: sc \\COMPUTER_NAME stop "SERVICE_NAME"
  3. Wait for the service to stop before starting. You can get the status with sc \\COMPUTER_NAME query "SERVICE_NAME".
  4. To start a service run: sc \\COMPUTER_NAME start "SERVICE_NAME"

Note: You can replace the COMPUTER_NAME with an IP address.

Full script with automatic waits

The batch script below will stop your service and wait for your service to be completely stopped before starting your service again. And, then wait for it to be fully running before continuing. In the script below, you have to modify the following before running it:

  • Assign your service to variable service_name.
  • Assign your computer name(hostname) or IP address to variable computer_name.
REM -- Change service_name and computer_name to your situation.
set service_name="W32Time"
set computer_name="Your hostname or IP"

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
)

REM -- Start service and wait until status is RUNNING.
sc \\%computer_name% start %service_name%
:loop2
sc \\%computer_name% query %service_name% | find "RUNNING"
if errorlevel 1 (
    timeout 1 /nobreak
    goto loop2
)

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.