Windows – Deleting all files from source directory after robocopy, but retaining those that cause errors

batchcommand linerobocopywindows

I plan to use robocopy to move files and folders from a directory on a server to a directory on a hard drive, using the following command,

robocopy [source] [destination] /e /move /xo

In the event of a file name conflict, I understand this to replace the files on the hard drive only if it is newer (or exactly the same age?), and then to delete the files that have been copied.

Ideally I would like the source directory to be cleared of files, but I suspect there may be a problem; if a file is not transferred (perhaps it is currently in use, or a newer version exists in the destination) then it will not be deleted.

In the case of an actual error in the copy process (e.g. if robocopy refuses to move a file that is in use), I cannot just add a subsequent command to delete the whole source directory as this could result in the loss of data that has not been transferred.

I plan to use this as a batch file that is executed as a scheduled task by Windows on a regular basis.

My question is therefore: is there a simple automated way to have robocopy delete the files that have either been transferred correctly (as it already does) or those for which newer copies already exist in the destination (which it does not currently do), whilst keeping the files that did not transfer due to some other error (e.g. permissions, file in use, etc.)?

Is there perhaps a simpler way to do this?

Best Answer

For operations like this I tend to use the mirror switch, (/mir), you can duplicate a directory to a second location, when things are moved out of the source they're also deleted from the destination. I realize that may not work in your situation though.

You may just need a way to clean files out of the source directory once they're considered old enough. Would something like a second job running forfiles work for you?

forfiles /d -14 /p C:\myfolder /C "cmd /c del @file"

This will clean out any files older than 14 days.

Related Question