winrar compress folders using batch

user3052799 picture user3052799 · Nov 30, 2013 · Viewed 9.9k times · Source

In a folder, I have some folders. I want to compress all the folders separately to the foldername.rar and delete the original files. I want to perform this function in batch.

I tried the ones given in other answers but they only compress the files if present, or do nothing. Here , I have to compress only folders to their respective archive. Please help

Answer

Sunny picture Sunny · Dec 1, 2013

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 folders under D:\test and you want each folder 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 D:\test /ad /s /b > D:\test\folders.txt
for /f %%f in (D:\test\folders.txt) do if not exist D:\test\%%~nf.rar %zip% D:\test \%%~nf.rar %%f
endlocal
exit

Explanation....

  1. It'll create .rar files of all the folders/subfolders under parent folder D:\test in the same parent folder.
  2. Then, it'll delete all the original folders/subfolders under parent folder D:\test 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