【问题标题】:Powershell [System.IO.Compression.ZipArchiveEntry] does not contain a method named 'ExtractToFile'Powershell [System.IO.Compression.ZipArchiveEntry] 不包含名为“ExtractToFile”的方法
【发布时间】:2018-11-19 09:45:02
【问题描述】:

我有一个 powershell 脚本,我想在其中提取特定条目。我似乎无法弄清楚如何克服在 .NET ZipArchiveEntry 对象上找不到扩展方法的错误。

我下面的脚本将运行并从 zip 中“写出”文件,但是当它到达 $entry.ExtractToFile($dst) 行时,会产生以下错误:

方法调用失败,因为 [System.IO.Compression.ZipArchiveEntry] 不包含名为“ExtractToFile”的方法。

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

$filesToExtract = @(
    "appsettings.json";
    "Content\cms\index.xml";
)
$archive = "C:\Users\User1\Desktop\archive.zip"
$dstRoot = "C:\Users\User1\Desktop\test"
$zip = [IO.Compression.ZipFile]::OpenRead($archive)
foreach($entry in $zip.Entries){
    if ($filesToExtract -contains $entry.FullName){
        $dst = [io.path]::combine($dstRoot, $entry.FullName)
        %{ "Extract ==> " + $dst }        

        $entry.ExtractToFile($dst)

    }
}
$zip.Dispose()

【问题讨论】:

  • 根据文档,it doesn't。这是一个扩展,但我不确定它在带有Add-Type 的 PowerShell 中如何工作。

标签: .net powershell scripting


【解决方案1】:

尝试使用 [System.IO.Compression.ZipFileExtensions]。如果提取文件已经存在,它将失败。

[cmdletbinding()]
Param()

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

$filesToExtract = @(
    "t.txt";
)
$archive = "$PSScriptRoot\t.zip"
$dstRoot = "$PSScriptRoot"
$zip = [System.IO.Compression.ZipFile]::OpenRead($archive)

foreach($entry in $zip.Entries){
    if ($filesToExtract -contains $entry.FullName){
        $dst = [io.path]::combine($dstRoot, $entry.FullName)

        if (Test-Path -Path $dst) { Remove-Item -Path $dst }

        Write-Verbose $("Extract ==> {0}" -f @($dst))
        [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $dst)
    }
}
$zip.Dispose()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 2015-09-28
    • 2012-12-22
    • 2017-09-15
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多