≡ Menu

Add a file to existing ZIP file using PowerShell

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.



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
Write-Host "Successfully added $NewFileToAdd to $ZIPFileName "
} catch {
Write-Warning "Failed to add $NewFileToAdd to $ZIPFileName . Details : $_"



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.

{ 4 comments… add one }
  • Curtis July 10, 2018, 6:45 pm

    Hey. This is great, thank you!
    Do you have a way where you could add a file to a subdirectory in the .zip?

    • Wintel Rocks July 25, 2018, 7:51 pm

      Curtis, I have tried that. Will make a post on it in future.

      • Windows User August 23, 2018, 8:08 pm

        Any updates on this? 😐

Leave a Comment