2

在批处理文件中,我正在尝试检查服务是否已启动,如果未启动则等待。

现在要检查服务是否正在运行,我这样做:

sc query "serviceName" | find /i "RUNNING"
if "%ERRORLEVEL%"=="0" (
    echo serviceName is running.
) else (
    echo serviceName is not running
)

麻烦的是errorlevel总是设置为0。可能是因为这个已知的Find bug。是否有任何替代方法来检查服务是否已启动,如果没有则等待?

4

5 回答 5

10

您可以使用Findstr而不是Find命令:

sc query "Service name" | findstr /i "RUNNING" 1>nul 2>&1 && (
    echo serviceName is running.
) || (
    echo serviceName is not running
)

您也可以使用wmic以下命令执行此操作:

wmic service where name="Service name" get State | Findstr /I "Running" 1>NUL 2>&1 && (
    echo serviceName is running.
) || (
    echo serviceName is not running
)

将来要注意的另一件事是,在比较数值时,您不应将表达式用引号括起来"",因此条件应如下所示:

If %ERRORLEVEL% EQU 0 () ELSE ()
于 2013-10-21T10:43:28.847 回答
8

Your code will work fine, if you aren't using Windows NT version 3.1 and Windows NT Advanced Server version 3.1 and your service name doesn't include running.

Perhaps it is within a loop and so you should use this (or delayed expansion):

sc query "serviceName" | find /i "RUNNING"
if not ERRORLEVEL 1 (
    echo serviceName is running.
) else (
    echo serviceName is not running
)
于 2013-10-21T11:19:14.000 回答
4

对我有用。您的 ERRORLEVEL 变量是否可能被覆盖或您的代码位于括号块中?尝试其中之一:

sc query "serviceName" | findstr /i "RUNNING"
if not errorlevel 1 (
    echo serviceName is running.
) else (
    echo serviceName is not running
)

或者

sc query "serviceName" | findstr /i "RUNNING" && (
    echo serviceName is running.
    goto :skip_not_w
) 
echo serviceName is not running
:skip_not_w

The cited bug is for windows nt (is this your OS?) and should be fixed already...If your os is NT , you should parse the output of the command with FOR /F to see it contains RUNNING or use FINDSTR

于 2013-10-21T10:48:12.370 回答
3
for /F "tokens=3 delims=: " %%H in ('sc query "serviceName" ^| findstr "        STATE"') do (
  if /I "%%H" NEQ "RUNNING" (
   echo Service not started
   net start "serviceName"
  )
)
于 2013-10-21T10:42:13.577 回答
1

Another way with a function:

:IsServiceRunning servicename
sc query "%~1"|findstr "STATE.*:.*4.*RUNNING">NUL

Usage Example:

Call :IsServiceRunning service && Service is running || Service isn't running
于 2013-10-21T11:49:43.677 回答