【问题标题】:Test if zip File extract command executed测试是否执行了 zip 文件提取命令
【发布时间】:2015-09-17 05:49:04
【问题描述】:

我想测试 zip 文件的条件是否被正确提取或在 PowerShell v4 中提取命令时出现任何错误。请更正我的代码。

Add-Type -AssemblyName System.IO.Compression.FileSystem

$file = 'C:\PSScripts\raw_scripts\zipfold\test.zip'
$path = 'C:\PSScripts\raw_scripts\zipfold\extract'

if ( (Test-path $file) -and (Test-path $path) -eq $True ) {
    if ((unzip $file $path)) {
        echo "done with unzip of file"
    } else {
        echo "can not unzip the file"
    }
} else {
    echo "$file or $path is not available"
}

function unzip {
    param([string]$zipfile, [string]$outpath)

    $return = [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
    return $return
}

此脚本提取一个 zip 文件,但显示“无法解压缩文件”。作为输出。

不确定 $return 变量的值是什么,我的 If 条件总是失败。

【问题讨论】:

  • 我的直觉是ExtractToDirectory 没有返回值所以它是空的
  • 感谢马特,我们可以通过任何其他方式实现这一目标,这对我来说非常有帮助
  • 一个简单的测量方法是使用带有$?的try块,如果最后一个操作成功则包含$TRUE,如果失败则包含$FALSE。我是说我认为你必须根据没有失败来假设成功。 类似的东西我建议stackoverflow.com/questions/10496885/…

标签: powershell if-statement unzip powershell-4.0


【解决方案1】:

documentation 证实了@Matt 的怀疑。 ExtractToDirectory() 被定义为 void 方法,因此它不返回任何内容。因为$return 始终是$null,其计算结果为$false

话虽如此,如果出现问题,该方法应该抛出异常,因此您可以使用try/catch 并在发生异常时返回$false

function unzip {
  param([string]$zipfile, [string]$outpath)

  try {
    [IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
    $true
  } catch {
    $false
  }
}

【讨论】:

    猜你喜欢
    • 2011-03-18
    • 2010-11-21
    • 2011-04-16
    • 2018-08-18
    • 1970-01-01
    • 2015-09-09
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多