简体   繁体   中英

Windows batch file for services

So, this file is supposed to check the status of 2 services and start them if they are found to be not running. It works well for the first service but how do I make it work for more than one services? Also, I want to be able to perform status check after it's started. Please let me know your thoughts.

net start | find "spooler" > nul 2>&1
if not .%errorlevel%.==.0. goto spoolersvc
goto nextSvc

:nextSvc
net start | find "BITS" > nul 2>&1
if not .%errorlevel%.==.0. goto BITSsvc
goto quit

:spoolersvc
net start "spooler"
echo spooler Service restarted at %TIME::=-% on %DATE:/=-% >> C:\scripts\isa\logs\spooler.log
echo

:BITSsvc
net start "BITS" 
echo Microsoft BITS Service restarted at %TIME::=-% on %DATE:/=-% >> C:\scripts\isa\logs\BITS.log
echo

:quit
exit

What you want is a batch file subroutine using call . Once you call a subroutine you can jump to the end of the file and the batch fill will pickup right where it left off. With this you can write a batch file that allows you to monitor and start any number of services.

set LOG_FILE=C:\scripts\isa\logs\spooler.log

call :CheckService spooler
call :CheckService BITS
goto :EOF

:CheckService
set SERVICE_NAME=%1

net start | find "%SERVICE_NAME%" > nul 2>&1
if not .%errorlevel%.==.0. goto :EOF

net start "%SERVICE_NAME%"
echo %SERVICE_NAME% Service restarted at %TIME::=-% on %DATE:/=-% >> %LOG_FILE%

net start | find "%SERVICE_NAME%" > nul 2>&1
if .%errorlevel%.==.0. (
    %SERVICE_NAME% Service started successfully at %TIME::=-% on %DATE:/=-% >> %LOG_FILE%
) else (
    %SERVICE_NAME% Service failed to start at %TIME::=-% on %DATE:/=-% >> %LOG_FILE%
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM