Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell [System.IO.Compression.ZipArchiveEntry] does not contain a method named 'ExtractToFile'

I have a powershell script where I'd like to extract specific entries. I can't seem to figure out how to get past the error where it can't find the extension methods on the .NET ZipArchiveEntry object.

My script below will run and will "write out" the files from the zip but when it gets to the $entry.ExtractToFile($dst) line, it produces the following error:

Method invocation failed because [System.IO.Compression.ZipArchiveEntry] does not contain a method named '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()
like image 964
Vee Avatar asked Aug 24 '26 01:08

Vee


1 Answers

Try using [System.IO.Compression.ZipFileExtensions]. It will fail if the extract file already exists.

[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()
like image 86
lit Avatar answered Aug 26 '26 17:08

lit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!