Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the proper way to copy files while preserving folder structure in powershell?

I can never seem to get this right.

I have an existing folder c:\MyApps\Websites\MySite that already has an existing website running in it. I've downloaded the latest bits which are 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 then it tries to put it in c:\MyApps\Websites\MySite\artifacts, but if it doesn't already exist it copies it properly. Not sure what's going on here. Any suggestions?

like image 573
Micah Avatar asked Jan 15 '23 23:01

Micah


1 Answers

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

robocopy $source $destination /E

It's shipped with Windows 7, so it's an internal command, so it's still a 'Powershell' way, imho, but if you're wanting to use the copy command, then you are very close, but your current implementation grabs the source folder and puts it inside target (ie the result would be C:\target\source\files, not C:\target\files). When you want to make the inside of target look like the inside of source, you need to do:

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

Notice the *, this grabs the contents of the source folder. If you want target to be cleared first, just do rm -r -fo C:\target\* before the copy.

Powershell doesn't handle long paths, so you will need to use robocopy anyway if you have a long filename or deep folders.

like image 85
SpellingD Avatar answered May 10 '23 08:05

SpellingD