【问题标题】:Catch an error inside a batch file (7-zip)在批处理文件中捕获错误 (7-zip)
【发布时间】:2011-10-13 09:32:19
【问题描述】:

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

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

存档被故意损坏。

cmd.exe 显示如下:

如何在我的代码中发现这个错误?

【问题讨论】:

    标签: windows batch-file error-handling runtime-error 7zip


    【解决方案1】:

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

    来自 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 
    

    所以:你可以这样做:

    "\Program Files\7-Zip\7z.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
    

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

    【讨论】:

      【解决方案2】:

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

      这是一个例子:

      "\Program Files\7-Zip\7z.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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-12
        • 2018-05-30
        • 1970-01-01
        • 2017-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多