Create / Extract zip file and overwrite existing files/content
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
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"