4

I have few extensions which I want to exclude from xcopy. I don't know in which folder/directory those may exist.

Below is the command I'm using:

xcopy /r /d /i /s /y C:\test1 C:\test2 /exclude:.txt+.exe

Anh help on this?

aschipfl
  • 33,626
  • 12
  • 54
  • 99
user2817712
  • 117
  • 2
  • 3
  • 5
  • 3
    `xcopy` exclude switch only accept files from where to read the list of elements to exclude. Create the file or use `robocopy` and `/xf` switch – MC ND Feb 22 '17 at 06:54
  • 3
    The `/EXCLUDE` option of `xcopy` does not really do what you want to, it does not exclude files with `.txt` and `.exe` extensions, it excludes all items whose full paths contain `.txt` or `.exe` at any position; for example, there is a source file `C:\test1\my.txt.files\file.ext`, it is going to be excluded also... – aschipfl Feb 22 '17 at 09:47
  • 1
    I agree with @aschipfl. Would be safer to use a FOR command to list the files and use the command modifier to check if the extension is valid. – Squashman Feb 22 '17 at 14:10

1 Answers1

16

What you are looking for is this:

xcopy /R /D /I /S /Y /EXCLUDE:exclude.txt "C:\test1" "C:\test2"

Together with the following content of exclude.txt:

.txt
.exe

However, the /EXCLUDE option of xcopy is very poor. It does not really exclude files with the given extensions, it actually excludes all items whose full paths contain .txt or .exe at any position. Supposing there is a source file C:\test1\my.txt.files\file.ext, it is going to be excluded also.


There are several methods to overcome this, some of which I want to show you:

  1. Use the robocopy command and its /XF option:

    robocopy "C:\test1" "C:\test2" /S /XO /XF "*.txt" "*.exe"
    
  2. Create a , using a for /F loop, together with xcopy /L, to pre-filter the files:

    set /A "COUNT=0"
    for /F "delims=" %%F in ('
        rem/ // List files that would be copied without `/L`; remove summary line: ^& ^
            cd /D "C:\test1" ^&^& xcopy /L /R /D /I /S /Y "." "C:\test2" ^| find ".\"
    ') do (
        rem // Check file extension of each file:
        if /I not "%%~xF"==".txt" if /I not "%~xF"==".exe" (
            rem // Create destination directory, hide potential error messages:
            2> nul mkdir "C:\test2\%%~F\.."
            rem // Actually copy file, hide summary line:
            > nul copy /Y "C:\test1\%%~F" "C:\test2\%%~F" && (
                rem // Return currently copied file:
                set /A "COUNT+=1" & echo(%%~F
            ) || (
                rem // Return message in case an error occurred:
                >&2 echo ERROR: could not copy "%%~F"!
            )
        )
    )
    echo         %COUNT% file^(s^) copied.
    
aschipfl
  • 33,626
  • 12
  • 54
  • 99