0

I want to automate compressing multiple files in a single directory, each with the same password, from the command line or with an app.

file1 -> file1(w/password).rar

file2 -> file2(w/password).rar

file3 -> file2(w/password).rar

The answer in Packing (WinRAR) with a password on a group of files is close to what I want, but way too complicated for my needs.

I know the reverse can be done easily from the command line.

Any thoughts? Thanks.

Community
  • 1
  • 1
11854761
  • 21
  • 5
  • Please note that https://stackoverflow.com is not a free script/code writing service. If you tell us what you have tried so far (include the scripts/code you are already using) and where you are stuck then we can try to help with specific problems. You should also read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask). – DavidPostill Mar 08 '17 at 22:00

1 Answers1

0

Here is a batch code for this simple task with an extra bonus:
The working directory can be passed to the batch file as first parameter.
The current directory is used if the batch file is started with no parameter.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "WorkingDirectory="
if "%~1" == "" goto ArchiveFiles

set "WorkingDirectory=%~1"
if "%WorkingDirectory:~-1%" == "\" (
    if exist "%WorkingDirectory%*"  pushd "%WorkingDirectory%" & goto ArchiveFiles
) else (
    if exist "%WorkingDirectory%\*" pushd "%WorkingDirectory%" & goto ArchiveFiles
)
echo Directory "%WorkingDirectory%" does not exist.
endlocal
goto :EOF

:ArchiveFiles
for /F "delims=" %%I in ('dir /A-D /B * 2^>nul') do (
    if /I not "%%~xI" == ".rar" (
        "%ProgramFiles%\WinRAR\Rar.exe" a -@ -cfg- -ep1 -idq -m5 -ma4 "-pPassword" -r- -s- -y -- "%%~nI.rar" "%%~fI"
    )
)
if not "%WorkingDirectory%" == "" popd
endlocal

This batch file ignores *.rar files already existing in the directory.

Open in program files folder of WinRAR the text file Rar.txt for details on used command a and the used switches.

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

  • call /? ... explains %~1
  • dir /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • popd /?
  • pushd /?
  • set /?
  • setlocal /?

Read also the Microsoft article about Using Command Redirection Operators explaining 2>nul whereby in this code the redirection operator > must be escaped with caret character ^ to be first interpreted as literal character on parsing FOR command line and as redirection operator on execution of DIR by FOR.

And read also the answer on Single line with multiple commands using Windows batch file to understand the meaning of operator & as used here on two command lines.

Community
  • 1
  • 1
Mofi
  • 46,139
  • 17
  • 80
  • 143