TAGS :Viewed: 8 - Published at: a few seconds ago

[ Prevent Powershell Copy-Item to create sub dir in target when target folder exists ]

I am copying folders with

Copy-Item $source $target -Force -Recurse -Container -ErrorAction Stop

If $target folder already exists, sub folder will be created under $target with same name and files will be copied there. How do I prevent this from happening?

Answer 1


Check if $target already exists, and add a trailing \* to $source if it does, so that only the contents of the folder are copied, not the folder itself. Like this:

if (Test-Path -LiteralPath $target) {
  $source += '\*'
}
Copy-Item $source $target -Force -Recurse -Container -ErrorAction Stop