简体   繁体   中英

Creating a batch script to shut down machine after multiple restart or stopping of services

I have created a batch script that is able to shut down the machine after multiple restarts or halts of a particular window service.

However, I have no idea about how to make the script work automatically instead of running it manually . I have tried testing the script file by setting it up under services.msc and setting it to run a program (batch file) after subsequent failures under this particular window service but when I stopped or restart the service 3 times manually, the batch script did not run at all .

So I'm thinking it could be that services.msc only recognizes failures before running the script instead of stopping or restarting the service. If so, is there any other way to run the script?

This is my batch script:

sc query "AVG Antivirus" | find "STOPPED" 
    if "%ERRORLEVEL%"=="3" 
    (
        shutdown.exe /s /t 00
    )

%errorlevel% doesn't "count" - it always gives 0 for "success" and NOT 0 (usually 1 , but depends on the command). So you have to implement an own counter:

set count=0
:loop
  sc query "AVG Antivirus" | find "STOPPED" && set /a count+=1
  if %count% geq 3 goto :continue
  timeout /t 5
goto :loop
:continue
shutdown.exe /s /t 00

|| works as "if previous command ( find here) failed then" (the opposite is && "if previous command was successful")

I'm not sure if you need the service to be RUNNING or STOPPED. Difference is just using && or || )

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