2013-10-21 73 views
2

在批處理文件中,我試圖檢查一個服務是否啓動,如果沒有,然後等待。檢查服務是否正在運行,而不使用查找命令

我們檢查,如果服務正在運行,我這樣做:

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

麻煩是ERRORLEVEL總是被設置爲0,可能是因爲此已知Find bug。 是否有任何替代方法來檢查服務是否已啓動,如果沒有,然後等待?

+2

避免「重置」%ERRORLEVEL%變量在你的代碼中。如果將其設置爲任何值,命令將正確設置錯誤級別值BUT NOT%errorlevel%變量。 –

回答

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 
) 
+0

aah.Brackets block.Didn't come to me。+ 1 – npocmaka

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

作品它可能是您的ERRORLEVEL變量,會自動覆蓋me.Is或者你的代碼是在括號阻止? 嘗試其中之一:

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

1

另一種方式用一個函數:

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

Usage Example: 

Call :IsServiceRunning service && Service is running || Service isn't running 
相關問題