2011-02-11 47 views
4

我在批處理文件中的標籤中執行以下命令: tasklist.exe/FI「USERNAME eq%USERDOMAIN%\%USERNAME%」/ FI「IMAGENAME eq%1」/ FI「PID eq%2」2> nul & & echo errorl:%errorlevel%退出批處理文件中任務列表的狀態?

%1正在進程運行,%2是它的PID。 即使進程及其PID匹配或不匹配,我在o/p中獲得「errorl:1」。

我不知道這裏有什麼錯。任何想法?

回答

6

在我看來,你不能使用ERRORLEVEL可言,
因爲任務列表總是返回即使PID找不到0。

我想,你必須解析任務列表的輸出。

@echo off 
setlocal enableDelayedExpansion 

set "cmd=tasklist.exe /FI "USERNAME eq %USERDOMAIN%\%USERNAME%" /FI "IMAGENAME eq %1" /FI "PID eq %2"" 

for /F "delims=*" %%p in ('!cmd! ^| findstr "%2" ') do (
    echo found %%p 
) 
1

變量%在執行該行之前展開,因此%errorlevel%將展開爲某個舊值。 (即之後的代碼& &執行所有的事實是你的線索,命令返回0)

您的選項有:

  • 使用%errorlevel%或下一行
  • 通話更正確IF errorlevel 1 ...setlocal ENABLEDELAYEDEXPANSION,然後再使用!errorlevel!

編輯: 我想任務列表是越野車和/或愚蠢的,當涉及到退出代碼,我寫了一些代碼,不使用退出代碼都:

@echo off 
if "%~1"=="SOTEST" (
    start calc 
    ping -n 2 localhost >nul 
    for /F "tokens=1,2 skip=3" %%A in ('tasklist /FI "IMAGENAME eq calc.exe"') do (
     call "%~0" %%A %%B 
    ) 
    call "%~0" dummy.exe 666 
    goto :EOF 
) 
goto main 


:IsTaskRunning 
setlocal ENABLEEXTENSIONS&set _r=0 
>nul 2>&1 (for /F "tokens=1,2" %%A in ('tasklist /FO LIST %*') do (
    if /I "%%~A"=="PID:" set _r=1 
)) 
endlocal&set IsTaskRunning=%_r%&goto :EOF 

:main 
call :IsTaskRunning /FI "USERNAME eq %USERDOMAIN%\%USERNAME%" /FI "IMAGENAME eq %1" /FI "PID eq %2" 
if %IsTaskRunning% gtr 0 (echo.%1:%2 is running) else (echo.%1:%2 is NOT running) 

運行它TEST.CMD SOTEST和它打印:

calc.exe:4852 is running 
dummy.exe:666 is NOT running 
+0

但是:IF ERRORLEVEL 1是真實的,如果錯誤級別爲1或1大,這可能是意外的行爲,我更喜歡IF%ERRORLEVEL%EQU 1或IF%ERRORLEVEL%GTR 1 – jeb 2011-02-11 14:00:58

+0

安德斯嗨,我已經在我的批處理腳本中使用了setlocal ENABLEDELAYEDEXPANSION,並按照您所描述的方式訪問參數。但它沒有工作。 – user613114 2011-02-11 14:03:31

9

您可以通過find命令管道任務列表並獲取關閉它的錯誤級別。

例子:

tasklist | find "firefox.exe" 
echo Error level = %ERRORLEVEL% 

REM If firefox is running, the errorlevel is set to 0 
REM If firefox is not running, errorlevel is set to 1 
0

解決這個,因爲

1) you can't get an errorlevel from tasklist, and 
2) you can't directly pipe it to a FIND 

只是它使用輸出重定向寫入到一個文件,並使用find來檢查文件。每次運行時,它都會覆蓋之前的迭代,因此不需要執行任何文件清理。驚人的簡單的便籤簿文件可以克服多少蝙蝠/ cmd文件的限制!

:TOP 
rem swap rems from good to bad to test 
set findvar=goodfile.exe   
rem set findvar=badfile.exe 
set scratchfile=scratch.txt 
tasklist /fi "status eq running" /fi "imagename eq %findvar%">%scratchfile% 
type %scratchfile% 
pause 
echo Looking for %findvar% 
find "%findvar%" %scratchfile% 
echo Error level = %errorlevel% 
pause 
IF errorlevel 1 GOTO BAD 
IF errorlevel 0 GOTO GOOD 
GOTO OTHER 

:BAD 
echo Errrlevel 1 - task not found 
PAUSE  
GOTO TOP 
:GOOD 
echo Errrlevel 0 - task is running 
pause 
GOTO TOP 
:OTHER 
echo something else ????? you blew it somewhere!