Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a batch script that copies one directory to another, replaces old files?

I'd like a batch script in Windows with which I can copy one directory to another. If this directory already exists, and then for each file that already exists in both with the same name and location, it should be overwritten, if it does not exists, it should just be added.

In the end it should be a batch script to which I can pass 2 arguments, source & destination.

like image 986
NomenNescio Avatar asked Mar 28 '12 09:03

NomenNescio


People also ask

Does batch copy overwrite?

If the copy command is run from within a batch job you do not need to use the /Y switch: it will overwrite existing files.

Does xcopy replace existing files?

Copy Files Without Overwrite Existing Files With xcopy Command on Windows. You can use xcopy command for copy and move files. Below command does that it copy files and paste to new destination without overwrite existing files.


2 Answers

In your batch file do this

set source=C:\Users\Habib\test
set destination=C:\Users\Habib\testdest\
xcopy %source% %destination% /y

If you want to copy the sub directories including empty directories then do:

xcopy %source% %destination% /E /y

If you only want to copy sub directories and not empty directories then use /s like:

xcopy %source% %destination% /s /y
like image 149
Habib Avatar answered Sep 23 '22 01:09

Habib


It seems that the latest function for this in windows 7 is robocopy.

Usage example:

robocopy <source> <destination> /e /xf <file to exclude> <another file>

/e copies subdirectories including empty ones, /xf excludes certain files from being copied.

More options here: http://technet.microsoft.com/en-us/library/cc733145(v=ws.10).aspx

like image 22
Uri Avatar answered Sep 20 '22 01:09

Uri