Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create / Extract zip file and overwrite existing files/content

Tags:

powershell

Add-Type -A System.IO.Compression.FileSystem
[IO.Compression.ZipFile]::CreateFromDirectory('foo', 'foo.zip')
[IO.Compression.ZipFile]::ExtractToDirectory('foo.zip', 'bar')

I found the code to create and extract .zip files via PowerShell from this answer, but because of my low reputation I cannot ask a question as a comment on that answer.

  • Creating - How to overwrite an existing .zip file without user interaction?
  • Extracting - How to overwrite existing files and folders without user interaction? (Preferably like robocopys mir function).
like image 831
Clacers Avatar asked Aug 10 '17 16:08

Clacers


2 Answers

PowerShell has built-in .zip utilities without needing to use .NET class methods in version 5 and above. The Compress-Archive -Path argument also takes a string[] type so you can zip multiple folders/files into the destination zip.


Zipping:

Compress-Archive -Path C:\Foo -DestinationPath C:\Foo.zip -CompressionLevel Optimal -Force

There is also an -Update switch.

Unzipping:

Expand-Archive -Path C:\Foo.zip -DestinationPath C:\Foo -Force
like image 177
Maximilian Burszley Avatar answered Oct 17 '22 22:10

Maximilian Burszley


PowerShell versions prior to 5 can execute this script

Thanks to @Ola-M for update.

Thanks to @maximilian-burszley for update.

function Unzip($zipfile, $outdir)
{
    Add-Type -AssemblyName System.IO.Compression.FileSystem
    $archive = [System.IO.Compression.ZipFile]::OpenRead($zipfile)
    try
    {
        foreach ($entry in $archive.Entries)
        {
            $entryTargetFilePath = [System.IO.Path]::Combine($outdir, $entry.FullName)
            $entryDir = [System.IO.Path]::GetDirectoryName($entryTargetFilePath)

            #Ensure the directory of the archive entry exists
            if(!(Test-Path $entryDir )){
                New-Item -ItemType Directory -Path $entryDir | Out-Null 
            }

            #If the entry is not a directory entry, then extract entry
            if(!$entryTargetFilePath.EndsWith("\")){
                [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $entryTargetFilePath, $true);
            }
        }
    }
    finally
    {
        $archive.Dispose()
    }
}

Unzip -zipfile "$zip" -outdir "$dir"
like image 8
yW0K5o Avatar answered Oct 17 '22 20:10

yW0K5o