Batch file to compress subdirectories

Түмэнзул Батжаргал picture Түмэнзул Батжаргал · Dec 26, 2013 · Viewed 21.8k times · Source

I am trying to write a batch script that will run automatically compressing subdirectories using winrar or 7-zip:

Example:

 My Pictures
    Pics1 (Pics1.zip)
        File1.jpg
        File2.jpg
        File3.jpg
    Pics2 (Pics2.zip)
        File4.jpg
        File5.jpg
    Pics3 (Pics3.zip)
        File6.jpg
        File7.jpg
    ...

How do i write script.

Answer

Sunny picture Sunny · Dec 26, 2013

(1) Using WinRAR:

WinRAR includes two command-line tools, rar.exe and unrar.exe, where rar.exe compresses and unrar.exe uncompresses files.

Both are located in the C:\Program Files\WinRAR folder in the installable version.

Assuming, if there are multiple subfolders under C:\MyPictures and you want each subfolder to get its own .rar file , in the parent folder.

From a batch file, this works for you:

@echo off
setlocal
set zip="C:\Program Files\WinRAR\rar.exe" a -r -u -df
dir C:\MyPictures /ad /s /b > C:\MyPictures\folders.txt
for /f %%f in (C:\MyPictures\folders.txt) do if not exist C:\MyPictures\%%~nf.rar %zip% C:\MyPictures \%%~nf.rar %%f
endlocal
exit

Explanation....

  1. It'll create .rar files of all the folders/subfolders under parent folder C:\MyPictures in the same parent folder.

  2. Then, it'll delete all the original folders/subfolders under parent folder C:\MyPictures and thus you'll be left only with the archives at the same place.

    • “a” command adds to the archive

    • “-r” switch recurses subfolders

    • “-u” switch. Equivalent to the “u” command when combined with the “a” command. Adds new files and updates older versions of the files already in the archive

    • “-df” switch deletes files after they are moved to the archive

If you want to keep the original subfolders, just remove the -df switch.

(2) Using 7-Zip:

7-Zip is a file archiver with a high compression ratio.7z.exe is the command line version of 7-Zip. 7-Zip doesn't uses the system wildcard parser and it doesn't follow the archaic rule by which . means any file. 7-Zip treats . as matching the name of any file that has an extension. To process all files, you must use a * wildcard.

Using 7zip command-line options in a batch file, below works for you:

@echo off
setlocal
for /d %%x in (C:\MyPictures\*.*) do "C:\Program Files\7-Zip\7z.exe" a -tzip "%%x.zip" "%%x\"
endlocal
exit

Where

  • -a archive or add

  • -t Type of archive