繁体   English   中英

是否有一种从嵌套批处理脚本中捕获错误代码(%errorlevel%)的简单方法?

[英]Is there an easy way to capture the error code (%errorlevel%) from a nested batch script?

我有一个嵌套的批处理脚本,我希望我的错误代码渗透到调用它的主批处理脚本。 我努力了

exit /b %errorlevel%

但是这个变量并没有让它回归。 被调用的批处理脚本中的ECHO'ing%errorlevel%给了我103,但主批处理脚本中的ECHO'ing%errorlevel%(执行方面的下一行)给了我0.这个问题之前已经被问到了,但这些帖子都没有对我有用。

编辑:由于写作不好,我修改了我的问题,并将添加代码供您查看。

这是主批处理文件。 除非我将条件更改为0以外的值,否则此处的if语句永远不会被命中:

call BuildInstaller.cmd %SourceDir% %TargetDir% %ProductVersion% %%I
if %errorlevel% neq 0 (
    ECHO %date% %time%: Build of %%I failed, halting >> %LOGFILE%
    exit /b %errorlevel%
)

这是BuildInstaller.cmd退出的地方。 我已经清理了打印件以避免混淆:

if %errorlevel% neq 0 (
    exit /b %errorlevel%
)

作为旁注,我也尝试过

set returnvalue=12

在被调用的批处理脚本中,但主批处理脚本中的ECHO'ing%returnvalue%始终是后面程序的一次执行。 如果有人知道这个子问题的答案,那就知道了。

您有经典的延迟扩展错误。 看这个例子:

call BuildInstaller.cmd %SourceDir% %TargetDir% %ProductVersion% %%I
if %errorlevel% neq 0 (
    ECHO %date% %time%: Build of %%I failed, halting >> %LOGFILE%
    exit /b %errorlevel%
)

这是BuildInstaller.cmd:

@echo off
setlocal EnableDelayedExpansion

if 1 == 1 (
   rem Inside a code block, %errorlevel% have the same value it had before the block
   rem (its %value% is NOT updated inside the block) so you need to use !errorlevel!
   rem in order to get the *updated* value

   verify set errorlevel = 1
   if !errorlevel! neq 0 (
      exit /b !errorlevel!
   )
)

exit /B

有关详细信息,请查找“延迟扩展”。

执行每个命令后设置errorlevel。 因此,错误级别0是创建错误级别103之后的语句的结果。

要说明多个批处理文件:

sub.bat:

 rem This is invalid argument for zip which sets errorlevel
 zip -QQ

test.bat的:

 @echo off
 call sub.bat
 echo %errorlevel%

第一行来自zip的示例输出:

zip error: Invalid command arguments (no such option: Q)
16

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM