簡體   English   中英

從Windows批處理腳本中的else塊執行的命令返回錯誤級別

[英]Command executed from else block in Windows batch script returning wrong errorlevel

我是批處理腳本的新手,雖然在Windows 7 pc中擺弄簡單的腳本,但仍堅持以下幾點-

command1  
echo %errorlevel%  
    if %errorlevel% neq 0 (  
                echo -- Error occured during command1 execution ---           
        goto :eof  
    )   else (   
               echo -- command1 execution was successful ---  
               command2   
               echo %errorlevel%   
               if %errorlevel% neq 0 (              
                   echo -- Error occured during command2 execution ---          
                   goto :eof  
               )    
             )      

在這里,命令1執行成功(單獨檢查),並且返回錯誤級別0(成功),而命令2執行失敗(單獨檢查),而不是不為零(失敗),返回錯誤級別為0。但是當我刪除else條件時,命令2執行返回1(失敗)。 好奇地知道原因。

如建議的那樣,現在我開始使用!errorlevel聲明setlocal enabledelayedexpansion而不是%errorlevel%! 並給出成功/失敗所需的錯誤級別。
但是現在我面臨另一個問題。 我正在調用另一個命令(假設用command3代替command2)。 它依次調用我的java類之一,該類拋出java.lang.StringIndexOutOfBoundsException。 但是在我的.bat文件中,它返回的錯誤級別為0,而不是1,而command3失敗了(單獨檢查)。 以下是我最新的腳本-

@echo off
setlocal enabledelayedexpansion
command1  
echo call !errorlevel!
    if !errorlevel! neq 0 (  
                echo -- Error occured during command1 execution ---           
        goto :eof  
    )
               echo -- command1 execution was successful ---  
               REM command3  
               java MyclassName > logfilename.log 2>&1                   
               echo call !errorlevel!   
               if !errorlevel! neq 0 (              
                   echo -- Error occured during command3 execution ---          
                   goto :eof  
               )                      
echo --- command3 Executoin was successful---

如何強制!錯誤級別! 在出現某些異常失敗時返回正確的值。 請幫忙。

您需要調用delayedexpansion [關於它的數百篇SO文章-使用搜索功能],以顯示括號內的一系列指令(也稱為“代碼塊”)中已更改的任何變量的運行時值。

使用當前代碼,如果要顯示 command2返回的實際錯誤,請使用

           CALL echo %%errorlevel%%

如果要在錯誤errorlevel運行時值上執行if ,則使用

           if errorlevel 1 (

IF ERRORLEVEL n如果errorlevel為n 或大於 IF ERRORLEVEL nIF ERRORLEVEL n為TRUE。 IF ERRORLEVEL 0因此始終為true。 IF NOT ERRORLEVEL 1是對errorlevel = 0的測試。

試試這個修改后的代碼版本,讓我們實際使用ifelse

@echo off
setlocal enabledelayedexpansion
command1 2>&1
echo !errorlevel!
if !errorlevel! neq 0 (  
         echo -- Error occured during command1 execution ---        
     ) else (
          echo -- command1 execution was successful ---
          command3 2>&1
          echo !errorlevel!
              if !errorlevel! neq 0 (              
                   echo -- Error occured during command3 execution ---          
               ) else (                     
                   echo --- command3 Execution was successful---
           )
      ) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM