How to use xcopy to add the date in the destination file?

Pherdindy picture Pherdindy · Apr 21, 2018 · Viewed 11.4k times · Source

This is my current code

xcopy "C:\Users\Asus\Desktop\Test\Test.MDB" "C:\Users\Asus\Google Drive\" /Y /H /E /F /I
exit

I need the code to do something like:

xcopy "C:\Users\Asus\Desktop\Test\Test.MDB" "C:\Users\Asus\Google Drive\Test (4-21-18).MDB" /Y /H /E /F /I
exit

I need to back up the files every 2 weeks in the task scheduler and I need the script to automatically add the date of the back-up. Also, I have looked at the list of commands (e.g. /Y /H /E) and I cannot find one that describes non-overwriting in the destination folder. I need the back-ups to pile up and not get deleted every time the code runs.

Answer

Spyros K picture Spyros K · May 9, 2018

You can create a bat file, get the current date in a variable and have this variable as part of the file name.

This bat file works:

for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate
set MyDate=%%x
set today=%MyDate:~4,2%-%MyDate:~6,2%-%MyDate:~2,2%

mkdir "C:\Users\Asus\Google Drive\Test (%today%).MDB"

xcopy "C:\Users\Asus\Desktop\Test\Test.MDB" "C:\Users\Asus\Google Drive\Test (%today%).MDB" /Y /H /E /F /I
exit

This code first saves the current date in "MyDate" variable. Then the desired date format is saved in "today" variable. Finally the content of the "today" variable is used as part of the file name that is passed in "xcopy" as an argument.

Mkdir makes sure that the directory is first created before xcopy is used. This prevents the xcopy question <F = file, D= directory>? that pops out. If a path refers to a file or directory that does not exist, xcopy considers it reasonable to first ask you what it is. Alternatively you could add a '\' in the end of the directory path to indicate that it is a directory.