6

When destination folder exists the right way of copying files is defined here

Copy-Item 'C:\Source\*' 'C:\Destination' -Recurse -Force

If destination folder doesn't exist, some files in the source subfolders are copied straight into destination, without keeping original folder structure.

Is there a way to have a single Copy-Item command to address both cases and persist folder structure? Or is it too much to ask from Powershell?

4
  • When testing it'll error the first time 'copy-item : Container cannot be copied onto existing leaf item.' however running it the exactly the same way will force it to copy items over the correct way without any issues keeping structure - i'm running 5.1 Commented Jun 19, 2018 at 8:58
  • I'm not getting any errors. First level subfolder contents are moved into root instead. /a/b/1.txt -> /a/1.txt Commented Jun 19, 2018 at 9:09
  • I imagine this is obvious but worth asking, are you running as admin and are you running as ISE? Commented Jun 19, 2018 at 9:17
  • I'm running as admin in Powershell command prompt and VSTS and see the same results. I think this is an old issue groups.google.com/forum/#!topic/… Commented Jun 19, 2018 at 9:45

2 Answers 2

2

You may want to use a if statement with test-path

this is the script i used to fix this problem

$ValidPath = Test-Path -Path c:\temp

If ($ValidPath -eq $False){

    New-Item -Path "c:\temp" -ItemType directory
    Copy-Item -Path "c:\temp" -Destination "c:\temp2" -force
}

Else {
      Copy-Item -Path "c:\temp" -Destination "c:\temp2" -force
     }
Sign up to request clarification or add additional context in comments.

2 Comments

Beat me to it. Always use Test-Path, as it's more efficient than a try/catch.
I would add -recurse.
0

Revised version of what Bonneau21 posted:

$SourceFolder = "C:\my\source\dir\*" # Asterisk means the contents of dir are copied and not the dir itself
$TargetFolder = "C:\my\target\dir"

$DoesTargetFolderExist = Test-Path -Path $TargetFolder

If ($DoesTargetFolderExist -eq $False) {
    New-Item -Path $TargetFolder -ItemType directory
}

Copy-Item -Path $SourceFolder -Destination $TargetFolder -Recurse -Force

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.