Search code examples
batch-filezip7zip

Add all Subfolders of a root folder and their contents to an existing Zip file


I have a directory structure similar to the following:

ROOT
  --> Site_01
    --> 2015
        --> 01
             --> more subfolders and files (thousands of log files)
  --> Site_02
    --> 2015
        --> 01
             --> more subfolders and files (thousands of log files)
  --> Site_03
    --> 2015
        --> 01
             --> more subfolders and files (thousands of log files)

And somewhere else, I have a possibly existing zip file, whose contents mirror the folder structure described above. What I'd like to do is script a batch file such that it zips up everything under ROOT into the possibly already-existing zip file.

If the zip file does not already exist, I want to create it, and if it does exist, I want to simply add the contents of ROOT to it.

What I've tried so far are variants of the following:

D:\ROOT>7z -u D:\archive\logs_app.zip *  
D:\ROOT>7z -up2q2r2x2y2z2w2 D:\archive\logs_app.zip *  

I don't care if there's a file in ROOT that already exists at the same location in the archive - the already-archived file can simply be overwritten. So, based on my perusal of 7Zip's Update Switch documentation, I left out all update options. But I get the error: Command Line Error: Too short switch:-u. And for the second, I figure that regardless of state, I want to compress the file and add it to the archive; that command gives me this output and error:

7-Zip [64] 9.38 beta  Copyright (c) 1999-2014 Igor Pavlov  2015-01-03

Command Line Error:
Unsupported command:
D:\archive\logs_app.zip

Solution

  • Here's the command that ended up working for me:

    D:\ROOT>7z a -tzip "D:\archive\logs_app.zip" * -aoa -mmt
    

    I found a great resource that ended up helping me figure this out here. My biggest problem was that I was not paying attention to the ordering of my command arguments and switches.

    1.) 7z a tells 7Zip to add files.
    2.) -tzip tells 7Zip to archive the files using the standard zip format, as opposed to a 7Zip format or an iso image.
    3.) "D:\archive\logs_app.zip" tells 7Zip the path to the existing archive to which I want to add files.
    4.) * tells 7Zip that I want to add any file to the existing archive from the current directory.
    5.) -aoa tells 7Zip to overwrite any matching existing files in the archive with whatever is in the source directory. NOTE: in many circumstances, this can be dangerous; there is no way to recover overwritten files!
    6.) -mmt tells 7Zip to use multiple threads. This will generally speed up the process, particularly when you're dealing with a large number of files.