Powershell Copy-Item:无法将容器复制到现有叶项上

Voi*_*tar 9 powershell file-transfer

我有一个 Powershell 脚本,其中一行看起来像这样:

Copy-Item \\[machine 1]\[path 1]\[directory 1]\ \\[machine 2]\[path 2]\ -recurse
Run Code Online (Sandbox Code Playgroud)

当我的脚本到达这一行时,出现以下错误:

Copy-Item : Container cannot be copied onto existing leaf item.
At C:\[script path]\[script name]:[line] char:5
+     Copy-Item \\[machine 1]\[path 1]\[directory 1]\ \\[machine 2] ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (\\[machine 1]\[path 1]\[directory 1]:String) [Copy-Item], PSArgumentException
    + FullyQualifiedErrorId : CopyContainerItemToLeafError,Microsoft.PowerShell.Commands.CopyItemCommand
Run Code Online (Sandbox Code Playgroud)

我找到了一个解决方法,即在 [路径 2] 下的 New-Item [目录 1],创建 Copy-Item 将填充内容的根目录,但这会导致另一个问题,即 Copy-Item 抱怨路径已经存在,尽管文件复制实际上成功了。Copy-Item 被宣传为一种“正常工作”的解决方案。我认为我的解决方法没有必要。文档的哪一部分会另有说明?为什么会发生这种情况?我的问题的最佳解决方案是什么?

小智 10

您问题的根本原因是目的地不存在。如果您在错误日志中查看上游,您将看到该消息。您需要创建目标文件夹:

if (-Not (Test-Path \\[machine 2]\[path 2]))
{
     md -path \\[machine 2]\[path 2]
}

Copy-Item \\[machine 1]\[path 1]\[directory 1]\ \\[machine 2]\[path 2]\ -recurse
Run Code Online (Sandbox Code Playgroud)