Create / Extract zip file and overwrite existing files/content

Viewed 31923
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).
2 Answers

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"
Related