How to test whether a service is running from the command line

后端 未结 14 1601
天涯浪人
天涯浪人 2020-12-12 18:59

I would like to be able to query whether or not a service is running from a windows batch file. I know I can use:

sc query \"ServiceName\"

相关标签:
14条回答
  • 2020-12-12 19:39

    Let's go back to the old school of batch programing on windows

    net start | find "Service Name"
    

    This will work everywhere...

    0 讨论(0)
  • 2020-12-12 19:39

    Use Cygwin Bash with:

    sc query "SomeService" |grep -qo RUNNING && echo "SomeService is running." || echo "SomeService is not running!"
    

    (Make sure you have sc.exe in your PATH.)

    0 讨论(0)
  • 2020-12-12 19:40

    You could use wmic with the /locale option

    call wmic /locale:ms_409 service where (name="wsearch") get state /value | findstr State=Running
    if %ErrorLevel% EQU 0 (
        echo Running
    ) else (
        echo Not running
    )
    
    0 讨论(0)
  • 2020-12-12 19:41
    SERVICO.BAT
    @echo off
    echo Servico: %1
    if "%1"=="" goto erro
    sc query %1 | findstr RUNNING
    if %ERRORLEVEL% == 2 goto trouble
    if %ERRORLEVEL% == 1 goto stopped
    if %ERRORLEVEL% == 0 goto started
    echo unknown status
    goto end
    :trouble
    echo trouble
    goto end
    :started
    echo started
    goto end
    :stopped
    echo stopped
    goto end
    :erro
    echo sintaxe: servico NOMESERVICO
    goto end
    
    :end
    
    0 讨论(0)
  • 2020-12-12 19:49

    Just to add on to the list if you are using Powershell.

    sc.exe query "ServiceName" | findstr RUNNING
    

    The command below does not work because sc is an alias to Set-Content within Powershell.

    sc query "ServiceName" | findstr RUNNING
    

    find also does not work on Powershell for some reason unknown to me.

    sc.exe query "ServiceName" | find RUNNING
    
    0 讨论(0)
  • 2020-12-12 19:50

    I would suggest WMIC Service WHERE "Name = 'SericeName'" GET Started

    or WMIC Service WHERE "Name = 'ServiceName'" GET ProcessId (ProcessId will be zero if service isn't started)

    You can set the error level based on whether the former returns "TRUE" or the latter returns nonzero

    0 讨论(0)
提交回复
热议问题