Search code examples
windowsbatch-filexcopy

xcopy batch folder tree


S:
cd \newclients
xcopy "s:\clients\*\MER" . /s /d
pause

This is my batch file. In my folder tree we have clients then names folders then MER folder. I want to be able to search the directory for the MER folder and copy that folder along with the client name before it. Is there a way to do this with batch files?


Solution

  • Using if exist should do the thing.

    pushd "s:\newclients"
    for /f "delims=" %%f in ('dir /b /ad "s:\clients\*"') do (
    if exist "s:\clients\%%f\MER\nul" ( xcopy "s:\clients\%%f\MER" "s:\newclients" /s /d )
    )
    popd
    pause
    

    Note: Add a slash if it's to check folder ie. if exist "s:\clients\%%f\MER\" ... or if exist "s:\clients\%%f\MER\nul" ...

    To suppress prompt about destination file/folder add /I in xcopy :

    /I    If in doubt always assume the destination is a folder
          e.g. when the destination does not exist.
    

    https://stackoverflow.com/a/33445866/