14

I am really new to batch file coding and need your help.

I've these directories:

c:\rar\temp1\xy.jpg
c:\rar\temp1\sd.jpg
c:\rar\temp1\dd.jpg

c:\rar\temp2\ss.jpg
c:\rar\temp2\aa.jpg
c:\rar\temp2\sd.jpg

c:\rar\temp3\pp.jpg
c:\rar\temp3\ll.jpg
c:\rar\temp3\kk.jpg

And I want to compress them to this

c:\rar\temp1\temp1.rar
c:\rar\temp2\temp2.rar
c:\rar\temp3\temp3.rar

How could this be done using WinRAR?

Mofi
  • 46,139
  • 17
  • 80
  • 143
adamzso
  • 141
  • 1
  • 1
  • 3

5 Answers5

32

This can be done also with WinRAR without using a batch file, not exactly as requested, but similar to what is wanted.

  1. Start WinRAR and navigate to folder c:\rar\.
  2. Select the folders temp1, temp2 and temp3 and click on button Add in the toolbar.
  3. As archive name specify now the folder for the RAR archives, for example c:\rar\.
  4. Switch to tab Files and check there the option Put each file to separate archive.
  5. Click on button OK.

WinRAR creates now three RAR archives with the file names temp1.rar, temp2.rar and temp3.rar in folder c:\rar\ with each archive containing the appropriate folder with all files and subfolders.

The list of files to add can be changed also on tab Files by entering for example *.txt in Files to exclude to ignore text files in the three folders on creating the archives.

And finally it makes sense to enter *.jpg on tab Files in edit field below Files to store without compression as JPEG files usually contain already compressed data and therefore WinRAR cannot really compress the data of the files further.


Here is also a batch file solution to move the files in all non-hidden subfolders of c:\rar\ and their subfolders into an archive file with name of the subfolder created in each subfolder as requested.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "RAREXE=Rar.exe"

if exist "%RAREXE%" goto CreateArchives
if exist "%ProgramFiles%\WinRAR\Rar.exe" set "RAREXE=%ProgramFiles%\WinRAR\Rar.exe" & goto CreateArchives
if exist "%ProgramFiles(x86)%\WinRAR\Rar.exe" set "RAREXE=%ProgramFiles(x86)%\WinRAR\Rar.exe" & goto CreateArchives
for /F "skip=2 tokens=1,2*" %%I in ('%SystemRoot%\System32\reg.exe query "HKLM\Software\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe" /v Path 2^>nul') do (
    if /I "%%I" == "Path" if exist "%%~K\Rar.exe" for %%L in ("%%~K\Rar.exe") do set "RAREXE=%%~fL" & goto CreateArchives
)
for /F "skip=2 tokens=1,2*" %%I in ('%SystemRoot%\System32\reg.exe query "HKCU\Software\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe" /v Path 2^>nul') do (
    if /I "%%I" == "Path" if exist "%%~K\Rar.exe" for %%L in ("%%~K\Rar.exe") do set "RAREXE=%%~fL" & goto CreateArchives
)
for /F "delims=" %%I in ('%SystemRoot%\System32\where.exe Rar.exe 2^>nul') do set "RAREXE=%%I" & goto CreateArchives

echo ERROR: Could not find Rar.exe!
echo(
echo Please define the variable RAREXE at top of the batch file
echo "%~f0"
echo with the full qualified file name of the executable Rar.exe.
echo(
pause
exit /B

:CreateArchives
set "Error="
for /D %%I in ("c:\rar\*") do (
    echo Creating RAR archive for "%%I" ...
    "%RAREXE%" m -@ -cfg- -ep1 -idq -m3 -msgif;png;jpg;rar;zip -r -s- -tl -y -- "%%I\%%~nxI.rar" "%%I\"
    if errorlevel 1 set "Error=1"
)
if defined Error echo/& pause
endlocal

The lines after set "RAREXE=Rar.exe" up to :CreateArchives can be omitted on definition of environment variable RAREXE with correct full qualified file name.

Please read the text file Rar.txt in the WinRAR program files folder for an explanation of RAR command m and the used switches. The question does not contain any information with which options the RAR archives should be created at all.

To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.

  • call /? ... explains %~f0 ... full name of batch file
  • echo /?
  • endlocal /?
  • exit /?
  • for /?
  • goto /?
  • if /?
  • pause /?
  • reg /?
  • reg query /?
  • set /?
  • setlocal /?
  • where /?

See also single line with multiple commands using Windows batch file for an explanation of the operator &.

Read the Microsoft documentation about Using command redirection operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on the three FOR command lines to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded reg or where command line with using a separate command process started in background.

Mofi
  • 46,139
  • 17
  • 80
  • 143
  • an issue. inside each zip there is still the parent folder. can i only want the child files? – zhuhang.jasper Mar 27 '23 at 16:53
  • @zhuhang.jasper The posted code uses *WinRAR* to create a RAR archive file and not a ZIP file as the console version `Rar.exe` of *WinRAR* cannot create a ZIP archive file at all. That can be done only with `WinRAR.exe` which would require some changes on the switches list. Neither `Rar.exe` nor `WinRAR.exe` add the directory itself into the archive file on using `-ep1` and let the directory path end with a backslash as my code does. See also: [Simply compress 1 folder in batch with WinRAR command line?](https://stackoverflow.com/a/24401436/3074564) – Mofi Mar 27 '23 at 17:15
  • 1
    @zhuhang.jasper But if you create the ZIP files with *WinRAR* using the GUI mode, you could select on tab __Files__ the option *Do not store paths* if the folders do not contain subfolders, just files to compress into ZIP archive files. Otherwise on folders containing also subfolders to add to the ZIP files, it is necessary to do the ZIP file creation from a PowerShell console or a Windows command prompt window. The GUI does not support selecting multiple folders and putting each folder with their subfolders and files into ZIP archives with the names of the selected folders. – Mofi Mar 27 '23 at 17:20
2

This script can work as well:

@echo off
for %%a in ("C:\rar\temp1" "C:\rar\temp2" "C:\rar\temp3") do (
    pushd "%%~a"
    "C:\Program Files\WinRAR\rar.exe" a -r temp.rar *
    popd
)
konsolebox
  • 72,135
  • 12
  • 99
  • 105
2

In Python v3.x:

  • Tested on Python v3.7
  • Tested on Windows 10 x64
import os

# NOTE: Script is disabled by default, uncomment final line to run for real.
base_dir = "E:\target_dir"
# base_dir = os.getcwd()  # Uncomment this to run on the directory the script is in.

# Stage 1: Get list of directories to compress. Top level only.
sub_dirs_raw = [os.path.join(base_dir, o) for o in os.listdir(base_dir) if os.path.isdir(os.path.join(base_dir, o))]

# Stage 2: Allow us exclude directories we do not want (can omit this entire section if we wish).
dirs = []
for d in sub_dirs_raw:
    if "legacy" in d or "legacy_old" in d:
        continue  # Skip unwanted directories
    print(d)
    dirs.append(d)

# Stage 3: Compress directories into .rar files.
for d in dirs:
    os.chdir(d)  # Change to target directory.
    # Also adds 3% recovery record using "-rr3" switch.
    cmd = f"\"C:\Program Files\\WinRAR\\rar.exe\" a -rr3 -r {d}.rar *"
    print(cmd)
    # Script is disabled by default, uncomment this next line to execute the command.
    # os.system(cmd)

Notes:

  • Script will do nothing but print commands, unless the final line os.system(cmd) is uncommented by removing the leading # .
  • Run the script, it will print out the DOS commands that it will execute. When you are happy with the results, uncomment final line to run it for real.
  • Example: if there was a directory containing three folders mydir1, mydir2, mydir3, it would create three .rar files: mydir1.rar, mydir2.rar, mydir3.rar.
  • This demo code will skip directories with "legacy" and "legacy_old" in the name. You can update to add your own directories to skip.
  • To execute the script, install Python 3.x, paste the lines above into script.py, then run the DOS command python script.py from any directory. Set the target directory using the second line. Alternatively, run the script using PyCharm.
Contango
  • 76,540
  • 58
  • 260
  • 305
  • 1
    Don't know why this had 0 votes. I always prefer a Python script over windows batch. Python is much more readable and powerful. I wish the target dir wouldn't be hardcoded though. So that you could put this script in the dir you want and just run it and it will assume that the target dir is the same dir you put the script in. – Curtwagner1984 Nov 06 '20 at 10:35
  • 1
    @Curtwagner1984 Sure, updated the script to natch. To put the script in the dir you want, and just run it and it will assume the target dir is the same dir the script is in, uncomment the fourth line in the script. – Contango Nov 06 '20 at 16:40
1

Below Script will compress each folder as a RAR file within the current directory with very useful info while compressing a large size of data.

@echo off
@for /D %%I in (".\*")  do echo started at %date% %time% compressing... "%%I" && @"%ProgramFiles%\WinRAR\Rar.exe" a -cfg- -ep1 -inul -m5 -r -- "%%I.rar" "%%I\" 
echo "Completed Successfully !!!"
pause 

enter image description here

Haseeb
  • 746
  • 7
  • 22
0

This should work it also checks if the files were compressed alright. You may need to change this part "cd Program Files\WinRAR" depending on where winrar is installed.

@echo Off
Cd\
cd Program Files\WinRAR
    rar a -r c:\rar\temp1\temp1.rar c:\rar\temp1\*.jpg c:\rar\temp1\
        if "%ERRORLEVEL%"=="0" ( Echo Files compressed
        ) Else Echo Failed
    rar a -r c:\rar\temp2\temp2.rar c:\rar\temp2\*.jpg c:\rar\temp2\
        if "%ERRORLEVEL%"=="0" ( Echo Files compressed
        ) Else Echo Failed
    rar a -r c:\rar\temp3\temp3.rar c:\rar\temp3\*.jpg c:\rar\temp3\
        if "%ERRORLEVEL%"=="0" ( Echo Files compressed
        ) Else Echo Failed
Pause
Badradish
  • 196
  • 1
  • 13