Robocopy – Exclude specific file from purge within subdirectory

robocopy

I want to exclude a specific file from being deleted while still performing a purge. The specific file is located within a subdirectory that does not exist in source.

Source:

folder1\
    file1.txt

Destination:

folder1\
    file1.txt
    folder2\
        dontdelete.txt
        delete.txt

If I use:

Robocopy C:\Source C:\Destination /e /purge /xf dontdelete.txt

Then Robocopy will delete folder2\ which contains that file, so in essence still deleting the dontdelete.txt file.

Source : C:\Source\
Dest : C:\Destination\
Files : *.*     
Exc Files : dontdelete.txt      
Options : *.* /V /L /S /E /DCOPY:DA /COPY:DAT /PURGE /R:1000000 /W:30 
----------------------------------------------------------------------------
                   0    C:\Source\
                   1    C:\Source\folder1\
*EXTRA Dir        -1    C:\Destination\folder1\folder2\
  *EXTRA File              0    delete.txt
  *EXTRA File              0    dontdelete.txt
          same             0    file1.txt

If I use:

Robocopy C:\Source C:\Destination /e /purge /xd folder2 /xf dontdelete.txt

Then Robocopy will not look inside folder2 at all for files that should be purged.

Source : C:\Source\
Dest : C:\Destination\
Files : *.*     
Exc Files : dontdelete.txt      
Exc Dirs : folder2      
Options : *.* /V /L /S /E /DCOPY:DA /COPY:DAT /PURGE /R:1000000 /W:30 
----------------------------------------------------------------------------
                   0    C:\Source\
                   1    C:\Source\folder1\
  *named dir      -1    C:\Destination\folder1\folder2\
          same             0    file1.txt

I have also tried using the entire path including the file with no difference in output.

Best Answer

Mention the full destination file's path to exclude it from purge. So, instead of

Robocopy C:\Source C:\Destination /e /purge /xf dontdelete.txt

use:

Robocopy C:\Source C:\Destination /e /purge /xf C:\Destination\folder1\folder2\dontdelete.txt

This works with both /purge and /mir. So /e /purge can be replaced with /mir in the command, as they are essentially the same. So the command can be:

Robocopy C:\Source C:\Destination /mir /xf C:\Destination\folder1\folder2\dontdelete.txt

Based on this answer.