检查服务是否正在运行,而不使用查找命令

batch file中,我试图检查一个服务是否启动,如果没有,然后等待。

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

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

麻烦是错误级别总是设置为0.可能是因为这个已知的查找错误 。 有没有其他的方法来检查服务是否开始,如果没有,然后等待?

如果您不使用Windows NT version 3.1 and Windows NT Advanced server version 3.1并且您的服务名称不包含running您的代码将正常工作。

也许它是在一个循环内,所以你应该使用这个(或延迟扩展):

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

您可以使用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 () 

适用于我。是否可能您的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 

引用的错误是为windows nt (这是你的操作系统?),应该已经修复…如果你的操作系统是新台币,你应该用FOR /F解析命令的输出,看看它包含RUNNING或使用FINDSTR

 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" ) ) 

另一种方式与功能:

 :IsServiceRunning servicename sc query "%~1"|findstr "STATE.*:.*4.*RUNNING">NUL Usage Example: Call :IsServiceRunning service && Service is running || Service isn't running