【问题标题】:PowerShell - suppress Copy-Item 'Folder already exists' errorPowerShell - 禁止复制项“文件夹已存在”错误
【发布时间】:2012-03-15 03:31:10
【问题描述】:

当我从具有子文件夹的文件夹运行递归 Copy-Item 到包含与原始文件夹相同的子文件夹的新文件夹时,当子文件夹已存在时会引发错误。

我该如何抑制这种情况,因为它是一种假阴性并且会使真正的失败更难被发现?

例子:

Copy-Item "C:\realFolder\*" "C:\realFolder_new" -recurse

Copy-Item : Item with specified name C:\realFolder_new\subFolder already exists.

【问题讨论】:

  • 添加 -Force 能解决问题吗?

标签: powershell copy-item


【解决方案1】:

您可以使用以下方法将错误处理行为设置为忽略:

Copy-Item "C:\realFolder\*" "C:\realFolder_new" -recurse -ErrorAction SilentlyContinue

不过,这也会抑制您确实想知道的错误!

【讨论】:

  • 是的......只有排序有帮助:) Copy-Item cmdlet中已经存在的东西是一个错误吗?似乎浪费了输出——如果它已经存在并且我即将创建它,那么谁在乎..至少给我一个 -slientOnExistingDirs 或 -verbose 开关,对吧?不过感谢您的帮助.. 我会考虑这个选项。
【解决方案2】:

您可以尝试捕获发生的任何错误,然后决定您是否关心它:

Copy-Item "C:\realFolder\*" "C:\realFolder_new" -recurse -ErrorVariable capturedErrors -ErrorAction SilentlyContinue
$capturedErrors | foreach-object { if ($_ -notmatch "already exists") { write-error $_ } }

【讨论】:

  • 谢谢,这行得通。今天终于有机会实现它并进行测试:)
【解决方案3】:

如果您将-Force 添加到您的命令中,它将覆盖现有文件并且您不会看到错误。

-Recurse 将替换每个文件夹和所有子文件夹中的所有项目。

Copy-Item "C:\realFolder\*" "C:\realFolder_new" -Recurse -Force

【讨论】:

  • 覆盖现有文件夹?还是只覆盖现有文件夹中的文件
  • 我必须同时做这两个 - -Recurse -Force- 这个让我工作。
猜你喜欢
  • 2015-07-16
  • 1970-01-01
  • 2013-07-19
  • 1970-01-01
  • 1970-01-01
  • 2019-02-04
  • 1970-01-01
  • 2013-06-24
  • 1970-01-01
相关资源
最近更新 更多