Search code examples
batch-filexcopy

Batch copy certain files with wildcard folders


I have limited skills/knowledge of bat files. Basically, I have used them to tidy up a folder for certain file types or to back up files to a dropbox folder.

I now would like to use them to find a file in a certain folder path and copy it to a local drive mirroring the folder path... The folder path has 50 folders and the are over 1000 subfolders. A couple of examples of the network location:
Reports\ASD01\ASD01_01 Reports\ASD01\ASD01_02 Reports\ASD01\ASD01_03 Reports\DVC05\DVC05_01 Reports\DVC05\DVC05_12 Reports\DVC05\DVC05_13 Reports\DVC06\DVC06_01

Each folder contains several files. I am interested in copying a pdf and a CSV from the subfolder to a mirrored folder on my local drive.

I have had a google and XCOPY can't copy folders as wild cards Reports\*\*\*.pdf

I would run the bat periodically to update any new files. I can't copy the entire contents of subfolder as they would be too large.

I hope I have given enough info and appreciate any help on this!


Solution

  • Assuming you want to recreatethe folder structure at the destination, then Robocopy is your call.

     Robocopy "C:\Source\Reports"  "C:\Destination\Reports" *.pdf /S /DCopy:T /NP /MT:64 /R:2 /W:2 /B
    

    The above will copy all PDF files from the Source to the destination and put them in the same subfolders.

    You can use the above As-Is in a cmd script, or paste it into the CLI.

    If you don't want thefolder structure, than a For loop is your pal.

    However you have tochangeit slightly depending on if you want to use it in the CLI or in aCMD Script

    CLI

    @For /F "Tokens=*" %A IN ('
      WHERE /R "C:\Source\Reports" /F "*.pdf"
    ') DO @(
      IF  NOT EXIST "C:\Destination\%~nxa" @(
        Copy /B /Y /F "%~fA" "C:\Destination\%~nxa"
      )  ELSE @(
         ECHO."C:\Destination\%~nxa" Already Exists, NOT Copying  "%~fA" due to conflict!
      )
    )
    

    CopyReplace.cmd

    @(
      ECHO OFF
      SETLOCAL EnableDelayedExpansion
      SET "_Src=C:\Source\Reports"
      SET "_Dst=C:\Destination"
      SET "_FileGlob=*.pdf"
    )
    
    For /F "Tokens=*" %%A IN ('
      WHERE /R "%_Src%" /F "%_FileGlob%"
    ') DO (
      IF  NOT EXIST "%_Dst%\%%~nxa" (
        Copy /B /Y /F "%%~fA" "%_Dst%\%%~nxa"
      )  ELSE (
         ECHO."%_Dst%\%%~nxa" Already Exists, NOT Copying  "%%~fA" due to conflict!
      )
    )