Batch File Copy and Move without overwriting

I'm trying to create a batch file (to run in the background) that will copy a single file without overwriting any file in the destination with the same name, and then move the file, again not overwriting if there is a file in the destination with the same name?

I'm using this at the moment, but it is overwriting.

copy %1 dest
move %1 dest

Solution 1:

Please try this. It works for a single file.

echo N | copy /-Y file1 file2

echo N | move /-Y file1 file2

Interestingly, it seems to work with wildcards as well. I tested that on x64 Windows 7.

Solution 2:

I am not clear on what you mean by moving the same file that was just copied, but in order to test if a file exists use an "IF" statement in a batch script like the following. (I explain in more detail about %~ farther down.)

IF EXIST %~dp2%~nx1 (echo file exists) ELSE (
robocopy %~dp1 %~dp2 %~nx1 /XN /XO /MOV>>testing.txt)

The following will work on Windows 7, Windows 8, Windows Server 2008, Windows Server 2008 R2, Windows Server 2012.

(For XP you'll have to get it from the Resource Kit, but oh no only 30 days of life left on that gem :) )

The following code copies a file from the source directory to the destination directory only if the destination file does not exist.

robocopy source_path dest_path filename /XN /XO

And adding /MOV will move the file.

If you want to use parameters the command would be something like this:

copyscript.bat C:\Dir1\filename.ext D:\path2\

With the copyscript.bat looking something this:

robocopy %~dp1 %~dp2 %~nx1 /XN /XO

If you want to send the output to a log then add >>logfile.txt like so:

robocopy %~dp1 %~dp2 %~nx1 /XN /XO>>logfile.txt 

If you want to Move the file instead of copy then like so:

robocopy %~dp1 %~dp2 %~nx1 /XN /XO /MOV 
  • %~dp1 equates to Directory and Path of the 1st parameter
  • %~dp2 equates to Directory and Path of the 2nd parameter
  • %~nx1 equates to file Name and eXtension of the 1st parameter
  • /XN eXcludes Newer files during the copy
  • /XO eXcludes Older files during the copy
  • /MOV MOVes the file instead of just copying
  • appends output results to a file instead of the cmd window (use only one > if you want to overwrite the log each time)

  • by default robocopy does not overwrite the file if the date time stamps are the same.

The Simon Sheppard’s site is a good batch script resource, the syntax for arguments is here. http://ss64.com/nt/syntax-args.html

Microsoft's robocopy info is here http://technet.microsoft.com/en-us/library/cc733145.aspx