As mentioned in the previous post, 7-Zip is a great piece of open-source compression software. Although you’ll most likely want to use the GUI version for daily use, power users may find the command line version useful for batch jobs. The command line version is bundled in the global installation package, so as far as you installed 7-Zip you do have the command line version installed, too.
Since the 9.x versions have been around for quite a while now and the 4.65 version is getting old, we’ll only cover the 9.x versions (at the time of writing, the 9.15 beta offered as a portable application in the above-mentioned post). If you want to stick with the 4.65 version I suggest you have a look as those examples or at the documentation (the Windows batch commands are of course the same but the 7-Zip parameters are a bit different, and also the executable itself has a different name: 7za.exe instead of 7z.exe).
For all those examples, we’ll assume that 7-Zip is installed in G:\UTILITIES\7-Zip\. Also, note that if you want to launch those commands from within a batch file instead of directly from the command line, you need to add an additional ‘%’ in front of ‘%A’ in the for commands. Finally, we are using LZMA2 with the maximum compression level. If you want LZMA, well, obviously just replace -m9=LZMA2 with -m9=LZMA. It’s actually easy to do a lot more customization, just check out 7-zip.chm in your 7-Zip installation folder.
Batch compressing individual files (non recursive)
This one will compress every file located within the current directory (one archive per file) and which have a bmp or txt extension:
for %A in (*.png *.txt) do "G:\UTILITIES\7-Zip\7z.exe" a -t7z -m9=LZMA2 "%A.7z" "%A"
Batch compressing individual files (recursive)
This one will individually (one archive per file) compress all files located within L:\My\Folder\ (and all sub-folders) and which have a txt or doc extension:
for /R "L:\My\Folder\" %A in (*.txt *.doc) do "G:\UTILITIES\7-Zip\7z.exe" a -t7z -m9=LZMA2 "%A.7z" "%A"
Also, note that all archives will be placed in the same folder as the file they contain (so there will be archives all around all sub-folders).
Batch compressing all folders of the current directory
This one will compress every folder of the current directory (one archive per first sub-level folder):
for /D %A in (*) do "G:\UTILITIES\7-Zip\7z.exe" a -t7z -m9=LZMA2 "%A.7z" "%A"
To write those commands the following pages were useful:
- FOR looping command at SS64.com Command line reference
- Windows batch – loop over folder string and parse out last folder name at stackoverflow
- 7-zip multiple files into multiple .zip and Batch compressing help on SourceForge.net 7-Zip forums