【问题标题】:expand-archive successfully expands, but oddly returns errorexpand-archive 成功扩展,但奇怪地返回错误
【发布时间】:2022-01-10 09:49:15
【问题描述】:

在一个脚本中,我试图解压缩一个 zip 文件,即使它成功地将文件解压缩到文件夹中,它也会返回错误。我收到 IF 语句的失败消息(下面的 sn-p)。我已经尝试过使用和不使用 -Force 选项并得到相同的结果。 zip 文件通过 sha256 哈希验证,解压后的文件夹大小与原始文件夹大小匹配,所以我知道它不是损坏的 zip 文件。任何想法这里发生了什么以及如何解决它?

脚本 sn-p:

# Extract downloaded zip file
if (Expand-Archive -LiteralPath $download_file_path -Force -DestinationPath $download_folder) {
  echo "File extraction successful" >> $log_path
} else {
  echo "File extraction FAILED! Exiting script." >> $log_path
  exit
}

控制台输出:

    Directory: C:\WINDOWS\TEMP


Mode                 LastWriteTime         Length Name                                                                 
----                 -------------         ------ ----                                                                 
d-----         1/10/2022   1:10 AM                app_data-20220110011021

自定义日志文件条目:

File extraction FAILED! Exiting script.

【问题讨论】:

    标签: powershell error-handling unzip


    【解决方案1】:

    您不应在if() 构造中使用Expand-Archive 来捕获任何可能的错误。 最好使用try{..} catch{..}

    # Extract downloaded zip file
    try {
        Expand-Archive -LiteralPath $download_file_path -Force -DestinationPath $download_folder -ErrorAction Stop
        Add-Content -Path $log_path -Value "File extraction successful" -PassThru
    } 
    catch {
        Add-Content -Path $log_path -Value "File extraction FAILED! Exiting script." -PassThru
        # you can view the error or write it to the log file:
        Write-Warning $_.Exception.Message
    }
    

    注意:

    • -ErrorAction Stop 使代码在终止和非终止错误上执行 catch 块。
    • 在 catch 块中,您可以通过 $_ 自动变量检查错误,如 $_.Exception.Message

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-31
      • 1970-01-01
      相关资源
      最近更新 更多