2
votes

Need Powershell Script for ZIP Extraction of only Specific Folder containing Style.CSS?

I have many ZIP files containing a mix of folders & files. I need a script to only filter and extract the entire FOLDER containing Style.CSS from the ZIP files.

There is a similar one using DotNetZip, but not quite to detect a unknown folder name which contains Style.css and then extracts only that folder.

Please advise. Thanks.

2

2 Answers

5
votes

Here is one way to get you started, using .Net Framework 4.5's ZipFile and ZipFileExtensions classes:

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

foreach($sourcefile in (Get-ChildItem -filter "*.zip"))
{
    Write-Host "Processing $sourcefile"
    $entries = [IO.Compression.ZipFile]::OpenRead($sourcefile.FullName).Entries

    #first pass to collect the paths of the folders with a Style.CSS file 
    $folders = $entries |
        ?{ $_.Name -eq 'Style.CSS' } |
        %{ split-path $_.FullName } | unique

    #second pass to extract just the files in those folders
    $entries |
        ?{ (split-path $_.FullName) -in @($folders) -and $_.Name } |
        %{
            #compose some target path
            $targetpath = join-path "$targetroot" (join-path $sourcefile.Name $_.FullName)
            #create its directory
            md (split-path $targetfilename) >$null 2>&1
            #extract the file (and overwrite)
            [IO.Compression.ZipFileExtensions]::ExtractToFile($_, $targetfilename, $true)
        }
}

Just define some targetroot or compose another targetpath