2010-12-06 30 views
30

只是偶然發現了一個奇怪的東西,%ERRORLEVEL%,並且想知道是否有人知道爲什麼以及是否有辦法解決它。實質上,看起來好像命令在if語句沒有設置變量的情況下執行。該ERRORLEVEL(如IF ERRORLEVEL 1,這是不同於IF%ERRORLEVEL%EQU 1)檢查似乎還在正常工作的,所以我可能可以解決它,但它仍然會是很好能夠打印錯誤級別。用於調試或其他。IF中的ERRORLEVEL

@echo off 
Set TESTVAR=1 

tasklist | find /I "IsntRunning.exe" > NUL 
echo OUTSIDE_IF %ERRORLEVEL% 

ThisWillSetErrorLevelTo9009ieNotRecognizedCommand 

tasklist | find /I "IsntRunning.exe" > NUL 
echo OUTSIDE_IF %ERRORLEVEL% 

ThisWillSetErrorLevelTo9009ieNotRecognizedCommand 

IF %TESTVAR% EQU 1 (
    Set ERRORLEVEL= 
    tasklist | find /I "IsntRunning.exe" > NUL 
    echo INSIDE_IF ERRORLEVEL %ERRORLEVEL% 

    IF ERRORLEVEL 1 (
     echo INSIDE_IF2 ERRORLEVEL GREQ 1 %ERRORLEVEL% 
    ) 
    IF ERRORLEVEL 2 (
     echo INSIDE_IF2 ERRORLEVEL GREQ 2 %ERRORLEVEL% 
    ) 
    IF ERRORLEVEL 3 (
     echo INSIDE_IF2 ERRORLEVEL GREQ 3 %ERRORLEVEL% 
    ) 
) 

tasklist | find /I "IsntRunning.exe" > NUL 
echo OUTSIDE_IF ERRORLEVEL %ERRORLEVEL% 

@echo on 

把在一個批處理文件並運行它產生這樣的輸出:

C:\Users\username\Documents\work>test.bat 
OUTSIDE_IF 1 
'ThisWillSetErrorLevelTo9009ieNotRecognizedCommand' is not recognized as an internal or external command, 
operable program or batch file. 
OUTSIDE_IF 1 
'ThisWillSetErrorLevelTo9009ieNotRecognizedCommand' is not recognized as an internal or external command, 
operable program or batch file. 
INSIDE_IF ERRORLEVEL 9009 
INSIDE_IF2 ERRORLEVEL GREQ 1 9009 
OUTSIDE_IF ERRORLEVEL 1 

相關文章:

+0

對不起,錯過了你的鏈接 – 2010-12-06 15:50:30

回答

33

嘗試在批處理文件的開頭使用setlocal enabledelayedexpansion,在IF內使用!ERRORLEVEL!。這似乎適用於我:

@echo off 
setlocal enabledelayedexpansion 
dir nul 
echo %ERRORLEVEL% 
if .1.==.1. (
    urklbkrlksdj - not a command 
    echo %ERRORLEVEL% 
    echo !ERRORLEVEL! 
) 
+3

哇,謝謝。這有效,甚至解釋它。作爲參考,我發現了一些鏈接:http://batcheero.blogspot.com/2007/06/how-to-enabledelayedexpansion.html | http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/setlocal.mspx?mfr=true – Srekel 2010-12-06 16:04:18