Windows – How to copy a directory, overwriting its contents if it exists using Powershell

powershellwindows 7

I have a directory Source with some files in it, which I would like to copy to a folder Destination. Destination may exist, and it may have files in it already. Any files with the same name as those in Source should be overwritten.

If I run this in Powershell:

Copy-Item Source Destination -Force -Recurse
Copy-Item Source Destination -Force -Recurse
Copy-Item Source Destination -Force -Recurse

Then the first line creates the folder .\Destination and copies .\Source into it, which is what I'd like to repeat for the next time. However, the second line copies .\Source into the new .\Destination folder (creating .\Destination\Source) instead, then the third line overwrites .\Destination\Source again.

How can I make it act like in the first case all the time? That is, overwrite .\Destination instead of copying into it?

Best Answer

So the problem is that

cp -r -fo foo bar

only works if bar does not exist and

cp -r -fo foo/* bar

only works if bar exists. So to work around, you need to make sure bar exists before doing anything

md -f bar
cp -r -fo foo/* bar
Related Question