Search code examples
batch-filexcopy

batch file xcopy to a partially unknown directory with a dot ( . ) in


Im trying to create a batch file that will copy a directory to another directory however, the directory I wish to copy too has a portion of the name randomly generated i.e. "jibberish.Directory1". is there a way to do this ?

I was trying something like:

XCOPY "%~dp0DATA\test" "%APPDATA%\Application1\Directory\*Directory1\" /E /C /R /I /K /Y 

but total fail. Any help would be greatly appreciated :) Thanks!


Solution

  • xcopy does not support wildcards in directory names. Therefore a for loop is additionally necessary for this task which is as follows:

    In folder C:\Temp there is the batch file DuplicateFolder.bat with the code below.

    The folder to duplicate is DATA\test in directory of the batch file.

    C:\Temp\DATA\test contains:

    • SubFolder1
      • FirstFile.txt
      • Second File.txt
    • Sub Folder 2
      • ListFile.csv
    • Readme.txt

    All these subfolders and files should be copied to each subfolder in %APPDATA%\Application1\Directory ending with a number after a dot.

    %APPDATA%\Application1\Directory contains for example:

    • Folder abc.1
    • Folder e-g.2
    • Folder h to k.3
    • Folder last.4
    • Folder not changed

    The last folder should be ignored as it does not contain a dot and a number at end.

    The result should be for example for the first subfolder Folder abc.1:

    • Folder abc.1
      • SubFolder1
        • FirstFile.txt
        • Second File.txt
      • Sub Folder 2
        • ListFile.csv
      • Readme.txt

    Code of DuplicateFolder.bat is:

    @echo off
    set "SourceFolder=%~dp0DATA\test"
    for /D %%F in ("%APPDATA%\Application1\Directory\*") do (
        if not "%%~xF" == "" %SystemRoot%\System32\xcopy.exe "%SourceFolder%" "%%~F" /E /C /Q /R /I /K /Y >nul
    )
    set "SourceFolder="
    

    This batch file just checks if folder name contains a dot without checking if string after dot - the "file extension" referenced with %%~xF - is really a number. This very simple test is very fast.

    For details about used command for and an explanation of the parameters and special loop variable references open a command prompt window, execute for /?, and read help output for this command in the console window.