One of the popular posts on this blog about managing ZIP/compressed/Archived Files is reading the contents from ZIP file. Several people asked how to add a file to existing ZIP file using PowerShell which I will cover in this blog post.
We will be using System.IO.Compression.FileSystem Assembly which contains the required classes to open an existing ZIP file and add new files to it. We have used the same assembly to read the contents of the ZIP file. To perform the add operation to existing zip file, we first need to open the ZIP file in Update mode and then add new file using CreateEntryFromFile method in System.IO.Compression.ZipFileExtension class. Don’t worry much about these classes and methods. I mentioned them for your understanding. You can explore further using these classes if you have any other requirements in managing the ZIP files.
Let us jump into the code now.
Code:
[CmdletBinding()] Param( [string]$ZIPFileName, [string]$NewFileToAdd ) try { [Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') | Out-Null $zip = [System.IO.Compression.ZipFile]::Open($ZIPFileName,"Update") $FileName = [System.IO.Path]::GetFileName($NewFileToAdd) [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,$NewFileToAdd,$FileName,"Optimal") | Out-Null $Zip.Dispose() Write-Host "Successfully added $NewFileToAdd to $ZIPFileName " } catch { Write-Warning "Failed to add $NewFileToAdd to $ZIPFileName . Details : $_" }
Usage:
Now let us see how to use this script. Save the above code into a file(Add-ToZipFile.ps1) or download the script from GitHub(https://github.com/techibee/PowerShell/blob/master/Add-ToZIPFile.ps1) and start using it with below example.
Add c:\test.txt to c:\myzip.zip file
PS C:\> .\Add-ToZIPFile.ps1 -ZIPFileName C:\myzip.zip -NewFileToAdd C:\test.txt
Hope this helps. I will add more examples related to zip files and Powershell in upcoming days.
Comments on this entry are closed.
Hey. This is great, thank you!
Do you have a way where you could add a file to a subdirectory in the .zip?
Thanks
Curtis, I have tried that. Will make a post on it in future.
Any updates on this? 😐
Hi, Nope. It is not available yet.
You can change script to
[CmdletBinding()]
Param(
[string]$ZIPFileName,
[string]$NewFileToAdd,
[string]$FileNameInZip
)
try {
[Reflection.Assembly]::LoadWithPartialName(‘System.IO.Compression.FileSystem’) | Out-Null
$zip = [System.IO.Compression.ZipFile]::Open($ZIPFileName,”Update”)
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,$NewFileToAdd,$FileNameInZip,”Optimal”) | Out-Null
$Zip.Dispose()
Write-Host “Successfully added $NewFileToAdd to $ZIPFileName ”
} catch {
Write-Warning “Failed to add $NewFileToAdd to $ZIPFileName . Details : $_”
}
Usage:
.\Add-ToZIPFile.ps1 -ZIPFileName C:\myzip.zip -NewFileToAdd C:\test.txt testFolder\test.txt