Shell – Powershell Copy-Item, from remote PC to remote PC

powershell

I am trying to copy a folder and subfolders from a server to a PC (both remotely).

$source='\\\server1\folder\\*'
$destination='\\\PC1\c$\temp\folder'
copy-item -path $source -destination $destination -recurse -force

This produces an error if I do it once, but if I run the same command again, it completes without error

Error is multiple instances of:

copy-item : container cannot be copied onto existing leaf item.
%
%
%
     + categoryinfo    : Invalidargument: (\\server1\folder:string) [copy-item] PSargumentexception
    +FullyQualifiedErrrId : CopyContainerItemToLeafError,Microsoft.powershell.Commands.CopyItemCommand

Like I said it completes without error the second time I run the command. What am I doing wrong that makes the error on the first run?

Best Answer

Set the source variable like this $source='\\server1\folder' and exclude the asterisk (*) from there as it is in the example provided. You don't need to escape the backslash (\) characters with an additional backslash so omit the additional backslashes in the UNC paths too.

Consider Using

$source='\\server1\folder'
$destination='\\PC1\c$\temp\folder'
Copy-Item -Recurse -Filter *.* -path $source -destination $destination -Force

Note: Use -Filter for the wildcard string pattern, etc.


Further Resources