How to check if a service is running via batch file and start it, if it is not running?

后端 未结 14 1619
暖寄归人
暖寄归人 2020-11-30 18:15

I want to write a batch file that performs the following operations:

  • Check if a service is running
    • If is it running, quit the batch
    • If
14条回答
  •  难免孤独
    2020-11-30 18:36

    I also wanted an email sent if the service was started this way so added a bit to @Ic code just thought I would post it in case it helped anyone. I used SendMail but there are other command line options How to send a simple email from a Windows batch file?

    set service=MyServiceName
    
    for /F "tokens=3 delims=: " %%H in ('sc query %service% ^| findstr "        STATE"') do (
      if /I "%%H" NEQ "RUNNING" (
    
        net start %service%
    
        for /F "tokens=3 delims=: " %%H in ('sc query %service% ^| findstr "        STATE"') do (
          if /I "%%H" EQ "RUNNING" (
            SendMail /smtpserver localhost /to me@mydomain.com /from watchdog@mydomain.com /subject Service Autostart Notification /body Autostart on service %service% succeded.
          ) else (
            SendMail /smtpserver localhost /to me@mydomain.com /from watchdog@mydomain.com /subject Service Autostart Notification /body Autostart on service %service% failed.
          )
        )
    
      )
    )
    

提交回复
热议问题