Powershell Copy-Item: Container cannot be copied onto existing leaf item

file-transferpowershell

I have a Powershell script with a line that looks like this:

Copy-Item \\[machine 1]\[path 1]\[directory 1]\ \\[machine 2]\[path 2]\ -recurse

When my script gets to this line, the following error occurs:

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

I've found a workaround, which is to New-Item [directory 1] under [path 2], creating the root that Copy-Item will populate with contents, but this causes another issue where Copy-Item complains that the path already exists, despite the file copy actually succeeding. Copy-Item is advertised as a sort of "just works" solution. I see no reason for my workaround to be necessary. What part of the documentation would indicate otherwise? Why does this happen? What is the best solution to my problem?

Best Answer

The root cause of your problem is that the destination does not exist. If you look upstream in your error log you will see that message. You need to create the destination folder:

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
Related Question