Home > Enterprise >  Deleting backup copy of file after the original has been deleted
Deleting backup copy of file after the original has been deleted

Time:09-12

I have original files on one drive (J:), and run a windows 10 batch file to make a backup copy on another drive (K:). I use this command and it works great:

xcopy "J:\files" "K:\files" /d /e /f /i /v

It creates new subdirectories and does not care about the file name at all.

Now my problem is that sometimes a file from the original location on J: gets deleted and the backup copy on K: is still there taking up space when I no longer need it.

I probably need to loop through all of the files in the backup K: directory and sub directories and delete the files which can not be found in the same path on original J: location. I have tried searching StackOverflow and have found nothing close to this other than looping files in a directory. I am probably using the wrong search terms, but this seems like a common problem which should already have a solution around here somewhere.

Any help pointing me to an existing post about this, or a suggestion for what code to use would be greatly appreciated!

CodePudding user response:

What you are asking (delete files in destination that are not present in source), is called "mirroring".

xcopy doesn't support mirroring.

A workaround is this:

You can run xcopy "K:\files" "J:\files" /L > filestodelete.txt (I have reversed the destination and the source) to obtain a list of files which exist in the destination folder but not in source folder. Then you can use a for loop to delete those files in the destination folder.

You have to consider that xcopy is no longer used anymore. It has been replaces by robocopy which use the same options as xcopy but has a lot more funtionality. For example, the parameter /MIR is used to mirror one folder to the other. As a bonus, robocopy is way faster.

/MIR parameter includes /PURGE parameter, which deletes dest files/dirs that no longer exist in source.

CodePudding user response:

The robocopy.exe with the mirror option makes an exact copy of the directory.

robocopy J:\files K:\files /mir
  • Related