Reputation: 14099
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?
Upvotes: 6
Views: 9700
Reputation: 2260
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
Upvotes: 0
Reputation: 586
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
}
Upvotes: 2