The Computer Oracle

How can I copy a directory, overwriting its contents if it exists using Powershell?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping

--

Chapters
00:00 How Can I Copy A Directory, Overwriting Its Contents If It Exists Using Powershell?
00:56 Answer 1 Score 1
01:30 Answer 2 Score 4
01:41 Accepted Answer Score 13
02:03 Answer 4 Score 5
02:30 Thank you

--

Full question
https://superuser.com/questions/544520/h...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#windows7 #powershell

#avk47



ACCEPTED ANSWER

Score 13


So the problem is that this:

Copy-Item -Force -Recurse foo bar

only works if bar does not exist and this:

Copy-Item -Force -Recurse foo/* bar

only works if bar exists. So to work around, you need to make sure bar exists before doing anything:

New-Item -Force -Type Directory bar
Copy-Item -Force -Recurse foo/* bar



ANSWER 2

Score 5


Steven Penny's answer https://superuser.com/a/742719/126444 doesn't delete original content of the target directory, just appending to it. I needed to completely replace the target folder with content of the source and created 2 functions:

function CopyToEmptyFolder($source, $target )
{
    DeleteIfExistsAndCreateEmptyFolder($target )
    Copy-Item $source\* $target -recurse -force
}
function DeleteIfExistsAndCreateEmptyFolder($dir )
{
    if ( Test-Path $dir ) {
    #http://stackoverflow.com/questions/7909167/how-to-quietly-remove-a-directory-with-content-in-powershell/9012108#9012108
           Get-ChildItem -Path  $dir -Force -Recurse | Remove-Item -force -recurse
           Remove-Item $dir -Force

    }
    New-Item -ItemType Directory -Force -Path $dir
}



ANSWER 3

Score 4


If you only want to copy contents of the "source" folder use

copy-item .\source\* .\destination -force -recurse



ANSWER 4

Score 1


Let's say that you Have the following structure of Directories

  • root

    • folder_a
      • a.txt
      • b.txt
      • c.txt
    • folder_b
      • a.txt
      • b.txt

    In The root folder you can achieve the results you want by the following sequence of commands:

    $files = gci ./folder_b -name
    cp ./folder_a/*.txt -Exclude $files ./folder_b

Only c.txt will be copied