windows 捕获批处理文件中的错误 (7-zip)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7752121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 18:15:53  来源:igfitidea点击:

Catch an error inside a batch file (7-zip)

windowsbatch-fileerror-handlingruntime-error7zip

提问by GG.

I have a batch file in which I execute the following line to list the contents of an archive:

我有一个批处理文件,我在其中执行以下行以列出存档的内容:

"\Program Files-Zipz.exe" l "\Backup Google Docs.7z"

The archive is intentionally corrupted.

存档被故意损坏。

cmd.exe displays this:

cmd.exe 显示:

enter image description here

在此处输入图片说明

How can I catch this error in my code?

如何在我的代码中捕获此错误?

回答by Benoit

Any program's exit code is stored in the %ERRORLEVEL%variable in a batch script.

任何程序的退出代码都存储在%ERRORLEVEL%批处理脚本中的变量中。

From the 7-zip manual:

来自 7-zip 手册:

7-Zip returns the following exit codes:

Code Meaning 
0 No error 
1 Warning (Non fatal error(s)). For example, one or more files were locked by some other application, so they were not compressed. 
2 Fatal error 
7 Command line error 
8 Not enough memory for operation 
255 User stopped the process 

So: you can do:

所以:你可以这样做:

"\Program Files-Zipz.exe" l "\Backup Google Docs.7z"
if errorlevel 255 goto:user_stopped_the_process
if errorlevel 8 goto:not_enough_memory
if errorlevel 7 goto:command_line_error
if errorlevel 2 goto:fatal_error
if errorlevel 1 goto:ok_warnings

Caution, if errorlevel Nchecks that %ERRORLEVEL%is greater or equal than N, therefore you should put them in descending order.

注意,if errorlevel N检查%ERRORLEVEL%大于或等于 N,因此您应该将它们按降序排列。

回答by Josh

Check if the ERRORLEVEL is set to 1 just after the call to 7z.exe and react appropriately. The ERRORLEVEL is the exit code from the last program that was run. An exit code of 1 or more indicates an error while zero indicates success. The IF ERRORLEVEL command checks if the exit is greater than or equal to the argument so IF ERRORLEVEL checks for an error level of one or more.

在调用 7z.exe 之后检查 ERRORLEVEL 是否设置为 1 并做出适当的反应。ERRORLEVEL 是最后运行的程序的退出代码。1 或更多的退出代码表示错误,而零表示成功。IF ERRORLEVEL 命令检查出口是否大于或等于参数,因此 IF ERRORLEVEL 检查错误级别是否为 1 或更多。

Here is an example:

下面是一个例子:

"\Program Files-Zipz.exe" l "\Backup Google Docs.7z" > nul
IF ERRORLEVEL 1 goto ziperror
@echo 7-Zip worked
goto :eof

:ziperror
@echo 7-Zip failed
goto :eof