从Windows批处理脚本中的else块执行的命令返回错误的错误级别

时间:2017-11-29 06:29:34

标签: java windows batch-file cmd windows-scripting

我是批处理脚本的新手,在摆弄我的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  
               )    
             )      

这里,command1执行成功(单独检查)并且它返回errorlevel 0(成功)而command2失败(单独检查)而不是没有零(失败)它返回errorlevel为0.但当我删除else时condition,command2执行返回1(失败)。很想知道原因。

正如所建议的,现在我在开始时使用!errorlevel声明setlocal enabledelayedexpansion而不是%errorlevel%!它在成功/失败方面给出了期望的错误水平 但现在我面临另一个问题。我正在调用另一个命令(假设command3代替command2)。它调用我的一个java类,它抛出了java.lang.StringIndexOutOfBoundsException。但是在我的.bat文件中,它返回errorlevel为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---

如何强制!错误级别!在失败时返回正确的值,但有异常。请帮忙。

2 个答案:

答案 0 :(得分:1)

您需要调用delayedexpansion [数百条SO文章 - 使用搜索功能],以显示在带括号的系列指令(也称为“代码块”)中更改的任何变量的运行时值。

使用您当前的代码,如果您想显示 command2使用

返回的实际错误
           CALL echo %%errorlevel%%

如果您想在运行时if上执行errorlevel,请使用

           if errorlevel 1 (
如果IF ERRORLEVEL n为n 或大于n ,则

errorlevel为TRUE。因此IF ERRORLEVEL 0总是如此。 IF NOT ERRORLEVEL 1是对errorlevel = 0的测试。

答案 1 :(得分:1)

尝试修改后的代码版本,让我们实际使用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---
           )
      )