Extract a certain file from zip via Powershell seems like not to look in sub folders

11,414

Solution 1

Here's how you can do it natively in newer versions of Powershell:

Add-Type -Assembly System.IO.Compression.FileSystem
$zip = [IO.Compression.ZipFile]::OpenRead($sourceFile)
$zip.Entries | where {$_.Name -like '*.update'} | foreach {[System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, "C:\temp\test", $true)}
$zip.Dispose()

Solution 2

Solved it by using the script below:

Add-Type -Path 'C:\dev\Libraries\DotNetZip\Ionic.Zip.dll'

$zip = [Ionic.Zip.ZIPFile]::Read($sourceFile)
foreach ($file in $zip.Entries) {    
if ($file -like "*.update") {
        $zip | %{$file.Extract("C:\temp\test", [Ionic.Zip.ExtractExistingFileAction]::OverWriteSilently)}
    }
}
Share:
11,414
Willem
Author by

Willem

BY DAY: Working on a high traffic website. BY NIGHT: Working on my own projects or watching Netflix ;-)

Updated on July 03, 2022

Comments

  • Willem
    Willem almost 2 years

    I'm very new to Powershell and especially to Powershell and ZIP files. I would like to unzip a specific file from the passed zipfile. To do so I have the code below. The code below should get a *.update from the zip.

    The issue I have is that the specific file is within another folder. When running the script it seems it won't look in the folder in the zip for more files.

    I've tried the GetFolder on the $item and/or foreach through the $item. So far no success. Anyone an idea or an direction to look in to?

    function ExtractFromZip ($File, $Destination) {
        $ShellApp = new-object -com shell.application
        $zipFile = $ShellApp.NameSpace($File)
        foreach($item in $zipFile.Items())
        {
            Write-Host $item.Name
    
            if ($item.GetFolder -ne $Null) {
                Write-Host "test"
            }
    
            if ($item.Name -like "*.update") {
                $ShellApp.Namespace($Destination).copyhere($item)
                break;    
            }
        }
    }
    
  • Mr. Mike
    Mr. Mike about 7 years
    I was looking at this today to solve an issue of my own, and I had one stumbling point that I'd like to clear up for future readers: The extraction function should read as ExtractToFile(zipArchive, destinationFileName, allowOverwriteYN). See MSDN for more
  • Santhos
    Santhos about 6 years
    I don't think this should be marked as the correct answer.
  • Bram
    Bram over 4 years
    Note that ExtractToFile() accepts a file name as destination. To extract multiple files the target file needs to be composed for each: $zip.Entries | Where-Object Name -like *.txt | ForEach-Object{[System.IO.Compression.ZipFileExtensions]::Ex‌​tractToFile($_, "$extractPath\$($_.Name)", $true)} (Source: theposhwolf.com/howtos/PowerShell-and-Zip-Files)