当目标文件夹存在时,防止Powershell Copy-Item在目标中创建子目录

时间:2014-11-11 15:09:39

标签: powershell

我正在用

复制文件夹
Copy-Item $source $target -Force -Recurse -Container -ErrorAction Stop

如果$ target文件夹已经存在,将在$ target下创建具有相同名称的子文件夹,并在那里复制文件。我该如何防止这种情况发生?

1 个答案:

答案 0 :(得分:2)

检查$target是否已存在,如果有\*,则添加尾随$source,以便仅复制文件夹的内容,而不是文件夹本身。像这样:

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