Using WINRAR with batch script

19.6k views Asked by At

I am new to scripting, can some please assist me,

I have batch file that

  1. Looks at the first 8 characters in the file name, creates and moves those files to new folder with first 8 characters as folder name.
  2. Then looks at folder created in step 1 for next four series of character (9,10,11,12)and create and move to another subfolder with next 4 characters as folder name.
  3. Then looks at folder created in step 2, for extension of every file and create and move to a new folder with extension as folder name.

For example, I have files that look like this

ABCEFGHI0703xyz.pdf
STUVWXYZ0805xyz.pptx

Move to folder

ABCEFGHI\0703\PDF
STUVWXYZ\0805\PPTX

Keeping in mind first 8 characters are random, next 4 character are year and month, and 9 types of extensions.

I am using this batch script to create these folders:-

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=C:\sourcedir"
SET "destdir=C:\sourcedir"
FOR /f "delims=" %%a IN (
  'dir /b /a-d "%sourcedir%\*" '
 ) DO (
 SET name=%%~na
 SET ext=%%~xa
 SET name=!name:~0,8!\!name:~8,4!\!ext:~1!
 MD "!name!" 2>nul
 MOVE "%sourcedir%\%%a" "!name!\" >nul
)
GOTO :EOF

Now I would like to add a WINRAR command to archive just the extension folders created in step 3, I am using this command to create the archives.

C:\ ABCEFGHI\0703\PDF>WINRAR A PDF C:\ ABCEFGHI\0703\PDF

Is it possible to add this command to the script?

1

There are 1 answers

9
MrPaulch On BEST ANSWER

Ok first you need to have rar.exe in a folder in %PATH%,

i'd suggest you put a link in your Windows\System32 folder like so:

mklink C:\Windows\System32\rar.exe "C:\Program Files\WinRAR\rar.exe"

then you can get to work.

As you already suggested, first create the desired directory tree and then just add the required files to your archive like so:

rar.exe a %ARCHIVE_NAME% MainFolder\*.pdf
rar.exe a %ARCHIVE_NAME% MainFolder\FolderA\*
rar.exe a %ARCHIVE_NAME% MainFolder\FolderB\*

Whereas %ARCHIVE_NAME% is the file name of your new target archive (such as foo.rar)

This will every *.pdf file in 'MainFolder' and everything in 'FolderA' and 'FolderB'. The directory tree will be preserved.

Also, you may want to check whether %ARCHIVE_NAME% already exists, since rar will just add the specified files to an existing archive (possibly overriding them)

Hope this clarifies some things for you.

Edit: doing this recursivly for unknown root directory

set ARCHIVE_NAME=%CD%\pdf_archive.rar
for /r %CD% %%d in ('PDF') do (
    if exist "%%d" (
        echo Archiving files in: %%d
        rar a "%ARCHIVE_NAME% "%%d"\*
    )
)

Now this will go into every subdirectory recursivly (starting from your current directory)

Then iw will look for folders called 'PDF' and if they exist it will archive every file in that folder to %ARCHIVE_NAME%