Copy-Item when destination folder exists or doesn't
Asked Answered
T

2

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?

Towboat answered 19/6, 2018 at 8:35 Comment(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.1Yellowgreen
I'm not getting any errors. First level subfolder contents are moved into root instead. /a/b/1.txt -> /a/1.txtTowboat
I imagine this is obvious but worth asking, are you running as admin and are you running as ISE?Yellowgreen
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/…Towboat
T
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
     }
Tacho answered 19/6, 2018 at 13:32 Comment(2)
Beat me to it. Always use Test-Path, as it's more efficient than a try/catch.Inferior
I would add -recurse.Exsanguine
S
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
Shoulder answered 27/9 at 19:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.