Home > database >  From batch file, I Need to recurse directories (and sub directories) and unzip every zip file found
From batch file, I Need to recurse directories (and sub directories) and unzip every zip file found

Time:03-17

From batch file, I Need to recurse directories (and sub directories) and unzip every zip file found into their current directory w/delete of archive

So, using a batch file or similar script method, i would like to recurse all directories and sub directories from a starting path location and for every zip file found, I want to unzip the contents in place (to the same directory as the zip file) and if successful, I want to delete the zip file.

I've not been doing bat files for quite a long time so looking for any help I can get.

What I've tried:

@echo off

echo ******
echo List all zip files using for /f
echo ******
for /f "tokens=*" %%r in ('dir *.* /ad /b') do for %%s in ("%%r\*.zip") do echo ---unzip %%s using output folder %%~dps

echo.
echo ******
echo List all zip files using for /d
echo ******
for /d %%r in (*) do for %%s in ("%%r\*.zip") do echo ---unzip %%s using output folder %%~dps

echo.
echo 1: extract to folders containing zip files - possible overwrites
echo 2: extract each zip to a folder named by the name of the zip file
choice /c 12
if not errorlevel 2 (

    for /d %%r in (*) do for %%s in ("%%r\*.zip") do "C:\Program Files\7-Zip\7z.exe" x -y "%%s" -o"%%~dps" && del "%%s"





) else (

rem ------ this is the alternative to extract each zip to its own folder
    for /d %%r in (*) do for %%s in ("%%r\*.zip") do (
        echo.
        echo ******
        echo *** Unzipping: %%s to folder: %%~dpns
        mkdir "%%~dpns"
        "C:\Program Files\7-Zip\7z.exe" x -y "%%s" -o"%%~dpns"  && del "%%s"
    )
rem ------

)
pause

exit /b

This code is working for the 1st directory, but doesn't recurse down further to subdirectories :

C:\dir1\aaa.zip
c:\dir2\bbb.zip
C:\Dir2\SUB1\AAA.zip    <====  my code is not extracting this zip in the subdirectory.

CodePudding user response:

... do (
 ... 7z x ....
 if errorlevel 1 (echo fail %%s) else (echo del %%s)
)

should fix your problem. 7zip appears to follow the rules and return errorlevel as 0 for success and non-zero otherwise. if errorlevel operates on the run-time value of errorlevel.

  • Related