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?

Kimi
  • 13,621
  • 9
  • 55
  • 84
  • 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 – Matthew Jun 19 '18 at 08:58
  • I'm not getting any errors. First level subfolder contents are moved into root instead. /a/b/1.txt -> /a/1.txt – Kimi Jun 19 '18 at 09:09
  • I imagine this is obvious but worth asking, are you running as admin and are you running as ISE? – Matthew Jun 19 '18 at 09:17
  • I'm running as admin in Powershell command prompt and VSTS and see the same results. I think this is an old issue https://groups.google.com/forum/#!topic/microsoft.public.windows.powershell/rpuLRCTCryI – Kimi Jun 19 '18 at 09:45

1 Answers1

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
     }
Bonneau21
  • 544
  • 1
  • 5
  • 20