# [SOLVED] Xcopy problem in batch file



## FFAA (May 4, 2010)

I am stumped with a batch file problem. I can accomplish what I want with COPY command, but it won't work when I replace it with XCOPY (which is what I really need).

I am trying to back up files AND insert the DATE into the filename.
The following line works perfectly:
copy c:\atemp\*.* c:\atemp\back*-%date:~4,2%-%date:~7,2%-%date:~10,4%.* 

However, when I try to run the exact same line using XCOPY, it doesn't insert the date.

My question is, whats the difference between COPY and XCOPY regarding how it interprets the %DATE% variable?


----------



## jcgriff2 (Sep 30, 2007)

*Re: Xcopy problem in batch file*

Hi - 

Since the backup directory is within the directory itself, XCOPY would give off an error = "Cannot perform a cyclic copy". Let XCOPY create a new directory in c:\ for the backup files.

Try this code for XCOPY - copy into *.bat file - 

```
[font=lucida console]
set x=%date:~4,2%-%date:~7,2%-%date:~10,4%
if not exist c:\atemp_backup\%x% then do (
	xcopy c:\atemp c:\atemp_backup\%x% /i /s /y
)  
[/font]
```
Then look in *c:\atemp_backup*. You'll find a folder with today's date on it and complete backup of c:\atemp.

You must run the batch script at an elevated admin level - RIGHT-click on the batch file, select "Run as Administrator".

Regards. . .

jcgriff2

.


----------



## FFAA (May 4, 2010)

*Re: Xcopy problem in batch file*

Thanks. This works. It is different from the approach I was attempting, but it will work. 

Can you explain why the code works for COPY but not for XCOPY?


----------



## jcgriff2 (Sep 30, 2007)

*Re: Xcopy problem in batch file*

Hi - 

Glad that code worked out for you.

"COPY" copies files only; XCOPY copies directories (folders) and files. 

The code you provided for the COPY command simply copies only files (not sub-directories and files found in those sub-directories) found in c:\atemp, renames them with the date and copies them to c:\atemp\backup. You would end up with a ton of files in c:\atemp\backup 

With XCOPY, if the destination back-up directory (folder) is a sub-directory of the source directory, it gives off the "Cannot perform a cyclic copy" error. If it ran, it would cause back-up sub-directories to be created within the back-up sub-directories and would not end until all hard drive space used up.

I hope that gives you a better understanding.

Regards. . .

jcgriff2

.


----------

