Restart Script, Part Deux

Wednesday, November 28, 2007
In a previous post I listed a batch file that will restart a given service, either on the local machine or a remote one. I rewrote the script to include processing for multiple computers. Simply create a file named "computers.txt" in the folder where you run RESTART.BAT from. Add each remote computer, one per line, to the computers.txt file.

Syntax for RESTART.BAT is: RESTART [\\Computer -OR- COMPUTERS.TXT] ServiceName

@echo off
If "%1" == "" Goto Syntax
If "%1" == "?" Goto Syntax
If "%1" == "/?" Goto Syntax
If "%2" == "" Goto RunLocal
If /I "%1" == "computers.txt" Goto RunMultiple
Goto RunRemote

:RunMultiple
FOR /F "tokens=1" %%i in (computers.txt) do Call :MRunRemote %%i %2
Goto End

:MRunRemote
echo %1 Find "\\" > nul
If %ERRORLEVEL% == 1 Goto Syntax
echo.
echo Working on %1...
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

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

:MStartLoop
sc %1 start %2 find "running" > nul
If %ERRORLEVEL% == 0 Goto :MStartLoop
echo The %2 service was started successfully.
Goto :EOF

: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 :StopLoop
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(s).
echo.
echo Syntax: RESTART [\\Computer -OR- COMPUTERS.TXT] ServiceName
echo.
echo COMPUTERS.TXT is a list of computers to run against. The file must exist
echo in the same working directory. Each computer must begin with \\ and be on
echo its own line.

:End
echo.

Please let me know if you find this useful.

No comments:

Post a Comment

Thank you for your comment! It is my hope that you find the information here useful. Let others know if this post helped you out, or if you have a comment or further information.