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

So the problem is that

cp -r -fo foo bar

only works if bar does not exist and

cp -r -fo foo/* bar

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

md -f bar
cp -r -fo foo/* bar

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
}

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

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