PowerShell: Extract specific files/folders from a zipped archive
Asked Answered
C

3

14

Say foo.zip contains:

a
b
c
|- c1.exe 
|- c2.dll 
|- c3.dll

where a, b, c are folders.

If I

Expand-Archive .\foo.zip -DestinationPath foo 

all files/folders in foo.zip are extracted.
I would like to extract only the c folder.

Claraclarabella answered 1/5, 2017 at 7:48 Comment(1)
I have same question... all answers below are ridiculously complex. MS why you hate me?Correna
V
18

try this

Add-Type -Assembly System.IO.Compression.FileSystem

#extract list entries for dir myzipdir/c/ into myzipdir.zip
$zip = [IO.Compression.ZipFile]::OpenRead("c:\temp\myzipdir.zip")
$entries=$zip.Entries | where {$_.FullName -like 'myzipdir/c/*' -and $_.FullName -ne 'myzipdir/c/'} 

#create dir for result of extraction
New-Item -ItemType Directory -Path "c:\temp\c" -Force

#extraction
$entries | foreach {[IO.Compression.ZipFileExtensions]::ExtractToFile( $_, "c:\temp\c\" + $_.Name) }

#free object
$zip.Dispose()
Viridi answered 1/5, 2017 at 8:30 Comment(2)
This worked like a charm and should be accepted. System.IO is not an "external library". It's .NETCoverup
You can use following regex to filter entries: $zip.Entries | Where-Object { $_ -match 'myzipdir/c/+.' }Blenny
C
2

This one does not use external libraries:

$shell= New-Object -Com Shell.Application 
$shell.NameSpace("$(resolve-path foo.zip)").Items() | where Name -eq "c" | ? {
    $shell.NameSpace("$PWD").copyhere($_) } 

Perhaps it can be simplified a bit.

Claraclarabella answered 1/5, 2017 at 12:30 Comment(1)
It did't work for me. It always returned empty result. How can I just show the content of the zip file? $i = $shell.Namespace("$(resolve-path .\myarc.zip)") then $i gets me a single object not enumeratable; I know that the path is right because when it's not right it returns null.Footcandle
L
0

Here is something that works for me. Of Course, you will need to edit the code to fit your objective

$results =@()

foreach ($p in $Path)
{


$shell = new-object -Comobject shell.application
$fileName = $p
$zip = $shell.namespace("$filename")

$Results +=  $zip.items()| where-object { $_.Name -like "*C*" -or  $_.Name -like 
"*b*"  }
}
foreach($item in $Results )
{

$shell.namespace($dest).copyhere($item)
}
Linear answered 26/10, 2018 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.