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

后端 未结 14 1587
暖寄归人
暖寄归人 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条回答
  •  萌比男神i
    2020-11-30 18:24

    Related with the answer by @DanielSerrano, I've been recently bit by localization of the sc.exe command, namely in Spanish. My proposal is to pin-point the line and token which holds numerical service state and interpret it, which should be much more robust:

    @echo off
    
    rem TODO: change to the desired service name
    set TARGET_SERVICE=w32time
    
    set SERVICE_STATE=
    rem Surgically target third line, as some locales (such as Spanish) translated the utility's output
    for /F "skip=3 tokens=3" %%i in ('""%windir%\system32\sc.exe" query "%TARGET_SERVICE%" 2>nul"') do (
      if not defined SERVICE_STATE set SERVICE_STATE=%%i
    )
    rem Process result
    if not defined SERVICE_STATE (
      echo ERROR: could not obtain service state!
    ) else (
      rem NOTE: values correspond to "SERVICE_STATUS.dwCurrentState"
      rem https://msdn.microsoft.com/en-us/library/windows/desktop/ms685996(v=vs.85).aspx
      if not %SERVICE_STATE%==4 (
        echo WARNING: service is not running
        rem TODO: perform desired operation
        rem net start "%TARGET_SERVICE%"
      ) else (
        echo INFORMATION: service is running
      )
    )
    

    Tested with:

    • Windows XP (32-bit) English
    • Windows 10 (32-bit) Spanish
    • Windows 10 (64-bit) English

提交回复
热议问题