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.
(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....
It'll create .rar files of all the folders/subfolders under parent folder C:\MyPictures in the same parent folder.
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
Here's how to do it in 7-zip.
Let's assume your files are in folder C:\Pictures\
. Then you can use the following batch command to create multiple archives with the same name as your directories.
FOR /D %%i IN (c:\Pictures\*.*) DO "c:\Program Files\7-Zip\7z.exe" a "%%i.zip" "%%i\"
This will compress each folder in the directory Pictures
. Change c:\Pictures
to the directory containing your folders. If 7-zip is installed to a different directory, change the "c:\Program Files\7-Zip\7z.exe"
to a directory where 7-zip is installed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With