Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy-Item when destination folder exists or doesn't

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?

like image 698
Kimi Avatar asked Jun 19 '18 08:06

Kimi


1 Answers

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
     }
like image 167
Bonneau21 Avatar answered Nov 15 '22 21:11

Bonneau21