2

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.

Community
  • 1
  • 1
Alex S
  • 242
  • 2
  • 17

2 Answers2

5

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

mousio
  • 10,079
  • 4
  • 34
  • 43
  • Thanks for a detailed script. I will check it out/ test it out. PS: I am familiar with Batch files as well as have done .NET programming in the past and a some of VBS back in the day. I havent' really used PowerShell a lot. What kind of FILE do I save your CODE into? and Execute? – Alex S Jan 12 '13 at 17:40
  • You can put the above e.g. in a file `myscript.ps1`. Then to execute it, you can run `powershell -f path_to\myscript.ps1` or make a shortcut for that; from within powershell, you can run it with `& 'path_to\myscript.ps1'`. – mousio Jan 12 '13 at 18:14
  • Thanks so much. Could I use this script & logic without .NET 4.5? With some other tool/ library with similar ability? 7zip as suggested below or DotNetZip? – Alex S Jan 13 '13 at 21:37
1

If .NET 4.5 isn't an option, use 7zip: http://sevenzip.sourceforge.jp/chm/cmdline/commands/extract.htm

Rex Hardin
  • 1,979
  • 2
  • 17
  • 16
  • I do not have NET 4.5 on the machine yet. I do have 7zip. How is it possible to script the "Required Logic" (to search for the correct file/folder location inside the Zip file) similar to the .NET 4.5 based code as been outlined by @mousio – Alex S Jan 12 '13 at 15:27