Search code examples
command-linebatch-filecmdxcopy

Using Windows commandline, how can I completely replace one folder with another?


So far I have it to where I can copy all the files from c:\Users\John\Folder1 to c:\Users\John\Folder2.

But I am looking to completely swap the folders.

e.g. Replace c:\Users\John\Folder1 with c:\Users\John\SomeFolder\Folder1.

I have this right now: xcopy c:\Users\John\SomeFolder\* c:\Users\John\Folder1 /s /i

This just copies all the files from the c:\Users\John\SomeFolder\Folder1 to c:\Users\John\Folder1 but leaves the files that had been there prior. I want the entire folder to be replaced. If the new folder I am copying no longer has those files, I want them deleted.

Sorry if this is confusing - any help is greatly appreciated.


Solution

  • I think you can create a batch file to do this.

    The pseudo-code:

    1. Erase contents of directory 1
    2. Copy the contents from directory 1 to directory 2

    The code: Create a file called swapFiles.bat in your notepad, and enter the following code:

    rd /s %1
    mkdir %1
    xcopy /s /i %2\* %1
    

    How to use it:

    swapFiles c:\Users\directory1 c:\Users\directory2
    

    directory1 is the old directory (i.e. the one that will be wiped out)

    Hope this helps you