在批处理文件中,我正在尝试检查服务是否已启动,如果没有,则等待。
现在检查服务是否正在运行,我这样做:
sc query "serviceName" | find /i "RUNNING"
if "%ERRORLEVEL%"=="0" (
echo serviceName is running.
) else (
echo serviceName is not running
)
麻烦是错误级别总是设置为0.可能是因为这个已知的Find bug。 是否有其他方法可以检查服务是否已启动,如果没有则等待?
答案 0 :(得分: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 ()
答案 1 :(得分:8)
如果您未使用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
)
答案 2 :(得分: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
引用的错误是windows nt
(这是你的操作系统吗?)并且应该已经修复了......如果你的操作系统是NT,你应该用FOR /F
解析命令的输出来查看它包含RUNNING
或使用FINDSTR
答案 3 :(得分: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"
)
)
答案 4 :(得分:1)
使用函数的另一种方法:
:IsServiceRunning servicename
sc query "%~1"|findstr "STATE.*:.*4.*RUNNING">NUL
Usage Example:
Call :IsServiceRunning service && Service is running || Service isn't running