Search code examples
batch-filecomparedosdirectory

batch script to recursively loop sub-directories and find missing files in 2 folders


I would like to compare recursively 2 folders and find missing files in them. I am using for loop to compare 2 folders but not able to search sub folders. Can somebody help?

Here is the code that I tried,

@echo off
if "%2" == "" GOTO Usage

cd /D %1
if errorlevel 1 goto usage

for %%x in (*.*) do if NOT exist %2\%%x echo missing %2\%%x
cd /D %2
for %%x in (*.*) do if NOT exist %1\%%x echo missing %1\%%x

goto end

:usage
echo Usage %0 dir1 dir2
echo where dir1 and dir2 are full paths
:end

Solution

  • try this, for explanation see comments in the code:

    @ECHO OFF &SETLOCAL
    SET "folder1=this"
    SET "folder2=that"
    
    REM delete variables
    FOR /f "delims==" %%a IN ('set "$"') DO SET "%%a="
    
    REM scanning folder1
    FOR /r "%folder1%" %%a IN (*) DO SET "$%%~nxa=%%~a"
    
    REM compare with folder2
    FOR /r "%folder2%" %%a IN (*) DO (
        IF NOT DEFINED $%%~nxa ECHO missing IN %folder1%: %%a
    )
    
    REM delete variables
    FOR /f "delims==" %%a IN ('set "$"') DO SET "%%a="
    
    REM scanning folder2
    FOR /r "%folder2%" %%a IN (*) DO SET "$%%~nxa=%%~a"
    
    REM compare with folder1
    FOR /r "%folder1%" %%a IN (*) DO (
        IF NOT DEFINED $%%~nxa ECHO missing IN %folder2%: %%a
    )
    
    ECHO Done.