Wednesday, October 31, 2007

Restart Services from the command line

Here's a handy batch file I wrote that stops and starts a service on the local or remote computer from the command line. You must have administrator rights on the target computer for the batch file to run properly.

@echo off
if "%1" == "" Goto Syntax
if "%1" == "?" Goto Syntax
if "%1" == "/?" Goto Syntax
if "%2" == "" Goto RunLocal

:RunRemote
echo %1 Find "\\" > nul
If %errorlevel% == 1 Goto Syntax
sc %1 query %2 Find "."
If %errorlevel% == 0 Goto End
sc %1 qc %2 Find "DISABLED" > nul
If %errorlevel% == 0 echo The requested restart is not valid for this service. & Goto End

:StopLoop
echo The %2 service is stopping...
sc %1 stop %2 > nul find "started" > nul
If %errorlevel% == 0 Goto Loop
echo The %2 service was stopped successfully.
echo.
echo The %2 service is starting...

:StartLoop
sc %1 start %2 find "running" > nul
If %errorlevel% == 0 Goto StartLoop
echo The %2 service was started successfully.
Goto End

:RunLocal
net stop %1 & net start %1
Goto End

:Syntax
echo.
echo Stops and starts a service on the local or remote computer.
echo.
echo Syntax: RESTART [\\Computer] ServiceName

:End
echo.
Copy the text above into Notepad and save it in your Windows folder as "Restart.bat". 9:43 AM