How to create a zip archive with PowerShell?

351,831

Solution 1

If you head on over to CodePlex and grab the PowerShell Community Extensions, you can use their write-zip cmdlet.

Since

CodePlex is in read-only mode in preparation for shutdown

you can go to PowerShell Gallery.

Solution 2

PowerShell v5.0 adds Compress-Archive and Expand-Archive cmdlets. The linked pages have full examples, but the gist of it is:

# Create a zip file with the contents of C:\Stuff\
Compress-Archive -Path C:\Stuff -DestinationPath archive.zip

# Add more files to the zip file
# (Existing files in the zip file with the same name are replaced)
Compress-Archive -Path C:\OtherStuff\*.txt -Update -DestinationPath archive.zip

# Extract the zip file to C:\Destination\
Expand-Archive -Path archive.zip -DestinationPath C:\Destination

Solution 3

A pure PowerShell alternative that works with PowerShell 3 and .NET 4.5 (if you can use it):

function ZipFiles( $zipfilename, $sourcedir )
{
   Add-Type -Assembly System.IO.Compression.FileSystem
   $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
   [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir,
        $zipfilename, $compressionLevel, $false)
}

Just pass in the full path to the zip archive you would like to create and the full path to the directory containing the files you would like to zip.

Solution 4

A native way with latest .NET 4.5 framework, but entirely feature-less:

Creation:

Add-Type -Assembly "System.IO.Compression.FileSystem" ;
[System.IO.Compression.ZipFile]::CreateFromDirectory("c:\your\directory\to\compress", "yourfile.zip") ;

Extraction:

Add-Type -Assembly "System.IO.Compression.FileSystem" ;
[System.IO.Compression.ZipFile]::ExtractToDirectory("yourfile.zip", "c:\your\destination") ;

As mentioned, totally feature-less, so don't expect an overwrite flag.

UPDATE: See below for other developers that have expanded on this over the years...

Solution 5

Install 7zip (or download the command line version instead) and use this PowerShell method:

function create-7zip([String] $aDirectory, [String] $aZipfile){
    [string]$pathToZipExe = "$($Env:ProgramFiles)\7-Zip\7z.exe";
    [Array]$arguments = "a", "-tzip", "$aZipfile", "$aDirectory", "-r";
    & $pathToZipExe $arguments;
}

You can the call it like this:

create-7zip "c:\temp\myFolder" "c:\temp\myFolder.zip"
Share:
351,831

Related videos on Youtube

Valentin V
Author by

Valentin V

Fraud detection at fingerprintjs.com Building open source tools and SaaS to empower developers to stop online fraud. Stop fraud, spam, and account takeovers with 99.5% accurate browser fingerprinting as a service.

Updated on May 13, 2022

Comments

  • Valentin V
    Valentin V almost 2 years

    Is it possible to create a zip archive using PowerShell?

  • x0n
    x0n almost 15 years
    Yep, and it uses 7z as the core library for most of its compression cmdlets. I know, becaues I implemented it ;) +1
  • Matt Hamilton
    Matt Hamilton almost 15 years
    lol nice work, x0n. I imlpemented the feed store provider in PSCX. Slightly less practical but tonnes of fun. :)
  • Greg Bray
    Greg Bray about 14 years
    Here is an example of using 7 zip with AES encryption from Powershell: codeblog.theg2.net/2010/02/…
  • mack
    mack about 11 years
    If it uses 7z, is it possible to zip using a password?
  • aboy021
    aboy021 almost 11 years
    If 7zip is in your path then all you need to write is "& 7z c:\temp\myFolder c:\temp\myFolder.zip"
  • bwerks
    bwerks over 10 years
    Does this actually need Powershell 3.0, or just .net 4.5? Looks very light on actual powershell features to me, instead just being .net programming.
  • noam
    noam over 10 years
    @bwerks see the 'edit' portion here
  • jpmc26
    jpmc26 almost 10 years
    If you don't want to install it, you can download the command line version instead. (Just look on 7-zip's Download page.) It's just an executable, and the command syntax is the same. The executable is a different name, though; it's 7za.exe for some reason. I've done this on a number of projects and have never been disappointed.
  • joshschreuder
    joshschreuder almost 10 years
    @SemiDemented write-zip [input file/folder] [output file]
  • Baodad
    Baodad over 9 years
    I was looking for a way to just compress a single large file, but apparently there isn't a method for this. I had to write code that would create a new directory, copy the single file there, compress that directory to a new zip file, then delete the directory to clean up.
  • Dherik
    Dherik about 9 years
    @Baodad, see my answer.
  • abarisone
    abarisone about 9 years
    Could you please elaborate more your answer adding a little more description about the solution you provide?
  • Ohad Schneider
    Ohad Schneider about 8 years
    PowerShell v5.0 has been officially released now. It also comes with Windows 10.
  • Lou O.
    Lou O. over 7 years
    I took a previous answer and improved it by adding overwrite option, not much more to say!
  • Kellen Stuart
    Kellen Stuart over 7 years
    Should've read that I needed the full path. Boy that was confusing! BTW this should be the accepted answer
  • starlocke
    starlocke over 7 years
  • starlocke
    starlocke over 7 years
    It's also easier to install via Chocolatey, though it still requires reboot - chocolatey.org/packages/PowerShell
  • AMissico
    AMissico over 7 years
    From Paragraph 2 of Compress-Archive Description: "...the maximum file size that you can compress by using Compress-Archive is currently 2 GB. This is a limiation of underlying API" However, if you use System.IO.Compression.ZipFile you can bypass this limitation.
  • TravisEz13
    TravisEz13 over 7 years
    The 2GB limit was inherited from System.IO.Compression.ZipFile. If the .NET framework you are using does not have this limit, the CmdLet should not hit this limit. I verified in the code.
  • Benoit Patra
    Benoit Patra about 7 years
    Powershell 5 comes with a Compress-Archive cmdlets that creates .zip blogs.technet.microsoft.com/heyscriptingguy/2015/08/13/…
  • Charlie Joynt
    Charlie Joynt almost 7 years
    Excellent. I was looking for a way to zip ONE file without using that shell.application business or 7-Zip / other separate utilities. I like the Using-Object function too, although I went for a shorter, quick-n-dirty approach without that.
  • Pramod
    Pramod over 6 years
    Use -OutputPath instead of -DestinationPath
  • Spencer
    Spencer over 6 years
    Simple and ease to understand, thanks! Perfect for my Jenkins deploy
  • BrainSlugs83
    BrainSlugs83 about 6 years
    @Pramod there is no -OutputPath parameter.
  • aaron
    aaron about 6 years
    the major problem of ZipPackage is it is not normal ZIP file, but contains a content xml file. see: [how to avoid [Content_Types].xml in .net's ZipPackage class - Stack Overflow](stackoverflow.com/questions/3748970/…)
  • noam
    noam about 6 years
    @aaron One more great reason not to use this ever again! You've got stiff competition for "the major problem" here ;)
  • akim
    akim about 6 years
    Compress-Archive builds a zip file with backslashes instead of forward ones. Did I miss something? The resulting zip file is a pain to use on other OSes.
  • Kevin Meier
    Kevin Meier almost 6 years
    "Compress-Archive" is not that great: it has an input file size limitation of 2 GiB.
  • Pluto
    Pluto over 5 years
    @Baodad Uh there is a method for this. I don't know why no one looks at the docs. Creating a zip: docs.microsoft.com/en-us/dotnet/api/… Adding a single file to the zip: docs.microsoft.com/en-us/dotnet/api/…
  • Pluto
    Pluto over 5 years
    Why would you use the featureless method?
  • DtechNet
    DtechNet over 5 years
    Remember that Powershell is .NET ... .NET has had the ZipFile class since implementation 4.5. Just use Reflection and you can grab the Compression.FileSystem assembly needed. Very simple. docs.microsoft.com/en-us/dotnet/api/… docs.microsoft.com/en-us/dotnet/api/… blogs.technet.microsoft.com/heyscriptingguy/2015/03/09/… I believe the accepted answer should be changed to another
  • DtechNet
    DtechNet over 5 years
    This is no longer a good accepted answer. However, users will find the thread helpful with the proper answers and various alternatives being posted elsewhere.
  • DtechNet
    DtechNet over 5 years
    This should be the accepted answer in order of date posted and precedent. As to your updated comment - there is truly a vast number of ways to do this now. I am faced with needing this functionality and I'm on PowerShell 4 the first thing I found is the native way. This was a good question in 2009. I still think there could have been further research presented in the question when originally asked.
  • Squazz
    Squazz over 5 years
    I tried a lot of things. Using .NET framework as one of the ways to do this. But this is by far the solution that has given me the least problems. Only drawback is the 2Gb limit
  • Pluto
    Pluto over 5 years
    This code relies on a shell application and then guesses 500ms to wait for it to finish... I'm not disagreeing that it works (in most cases). But it creates popups as you use it in every case where adding a compressed file takes some amount of time (easily reproduced with adding large files or working with large zips). Also if any zip operation is slower than whatever sleep time specified, it'll fail to add the file and leave behind a popup dialog box. This is terrible for scripting. I also downvoted the other answer that relies on a COM object because it doesn't address these pitfalls.
  • SebK
    SebK over 5 years
    I tried with .net and Powershell tools for way too long until going the 7zip path which worked right away. Simple foreach loop on $file does the trick & "C:\Program Files\7-Zip\7z.exe" a -tzip ($file.FullName+".zip") $file.FullName
  • Roman Starkov
    Roman Starkov about 5 years
    Compress-Archive creates broken archives, sadly this issue hasn't been fixed in 2 years since it was reported, and a pull request has been ignored for 6 months.
  • Scott Centoni
    Scott Centoni about 5 years
    It appears the code to fix this slash/backslash broken archive problem github.com/PowerShell/Microsoft.PowerShell.Archive/pull/62 was merged on 2019-02-19.
  • Rafael Kitover
    Rafael Kitover about 4 years
    Thank you for this, this is perfect. Especially compared to the Compress-Archive cmdlet which is badly designed and doesn't have a good way of specifying paths INSIDE the zip.
  • nivs1978
    nivs1978 about 4 years
    Why bloat your computer with extensions, when you can use the built in Compress-Archive
  • s31064
    s31064 over 3 years
    I thought I finally found the answer to my problem when I saw this, but no matter what I do, WinRar won't run. If I use a batch file to run it, everything's fine, but if I try to run that batch file from a PowerShell script, nothing happens, it just goes on to the next part of the script which uploads the file to an FTP server.
  • s31064
    s31064 over 3 years
    I tried using this function as is, and it does nothing. I don't get it. My $Arguments: [Array]$arguments = 'a', '-ag-YYYY-MM-DD-NN', '-dh', '-ed', '-ep3', '-ilogE:\Logs\WinRar\backup.log', '-INUL', '-r', '-y', 'E:\UsageWebLogs\Weblogs', 'W:\', 'X:\', 'Y:\', 'Z:\';
  • Dominik
    Dominik about 2 years
    Thanks for these examples. Is it also possible to e.g. get all xml files from multiple child folders, and zip them? I just created stackoverflow.com/questions/71934727/… and am failing with this. Would be great to see an example / answer :)
  • Jeter-work
    Jeter-work almost 2 years
    There is already an accepted answer. This answer is not new, there are already multiple .NET answers based around System.IO.Compression.ZipFile.