Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

zip

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;    
        }
    }
}
like image 325
Willem Avatar asked Sep 11 '15 14:09

Willem


2 Answers

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()
like image 120
Arithmomaniac Avatar answered Oct 10 '22 07:10

Arithmomaniac


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)}
    }
}
like image 39
Willem Avatar answered Oct 10 '22 08:10

Willem