Willem
Willem

Reputation: 418

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

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;    
        }
    }
}

Upvotes: 5

Views: 13772

Answers (2)

Arithmomaniac
Arithmomaniac

Reputation: 4804

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()

Upvotes: 23

Willem
Willem

Reputation: 418

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)}
    }
}

Upvotes: 1

Related Questions