What is the correct way to copy files while maintaining the folder structure in powershell?

I can never get it right.

I have an existing folder c:\MyApps\Websites\MySite , in which an existing website is already running. I downloaded the last bits located under c:\temp\MySite\artifacts .

when i try to run this

 $source "c:\temp\MySite" $destination "c:\MyApps\Websites\MySite" copy-item $source $destination -recurse -force 

if c:\MyApps\Websites\MySite already exists, he tries to put it in c:\MyApps\Websites\MySite\artifacts , but if it does not exist, it copies it correctly. Not sure what's going on here. Any suggestions?

+4
source share
1 answer

Just use the robocopy command. It is designed for this kind of thing.

robocopy $source $destination /E

It comes with Windows 7, therefore it is an internal command, therefore it is still โ€œPowershellโ€, imho, but if you want to use the copy command, you are very close, but your current implementation captures source and puts it inside target (i.e. E. The result will be C:\target\source\files , not C:\target\files ). If you want the inside of target look like inside source , you need to do:

cp C:\source\* C:\target -r -fo

Note * , this captures the contents in the source folder. If you want to clear the target first, just do rm -r -fo C:\target\* before the copy.

Powershell does not handle long paths, so you will need to use robocopy if you have a long file name or deep folders.

+9
source

All Articles