Powershell – How to copy a file to network resources using UNC paths

filesystemspowershellscriptingunc

I'm trying to do something pretty simple, and conceptually it should work, but it doesn't seem to, and I'm not sure why. I have a file I need to copy to multiple folders on multiple servers. I've been searching and trying different solutions all morning. Here's what I have that I think should work:

$servers = @("\\server1.domain.com","\\server2.domain.com","\\server3.domain.com","\\server4.domain.com")

$dests = @("\E$\path1","\E$\path2","\E$\path3","\E$\path4","\E$\path5")

$file = "C:\Users\user\file.txt"

foreach ($server in $servers)
{net use $server /USER:domain\username password
{foreach ($dest in $dests)
{copy-item -Path $file -Destination $server$dest}}}

The logic is that it will hit the first foreach, get the first servername, do a net use to cache my credentials on the computer, hit the second foreach, get the first path, then copy the file to the first path on the first server, then copy the file to the second path on the first server, etc. etc. At the end of the paths, it will return to the first foreach, move onto the second server, and go through the list of paths on the second server, and on and on.

I've seen similar posts other places where they don't use the second foreach, but I tried that and it didn't work, like this:

foreach ($server in $servers)
{net use $server /USER:domain\username password
{copy-item -Path $file -Destination $server$dest}}}

Thank you for any help anyone can give me on this. I'm sure it's something really simple that I'm just missing.

Best Answer

When using network resource file systems, and UNC paths, you should use the filesystem:: PSProvider in Powershell. Here's a couple examples:

Test-Path "filesystem::\\127.0.0.1\c$"
Test-Path "filesystem::\\$env:computername\c$"

Adapting this process to your code should be as simple as:

foreach ($server in $servers){

    net use $server /USER:domain\username password

    foreach ($dest in $dests){

        copy-item -Path $file -Destination "filesystem::$server$dest"

    }#End foreach ($dest in $dests)

}#End foreach ($server in $servers)

Remember, as a powershell professional your code should be as easily read as possible. As with all professional writing, style matters.

Also, you should look into using Get-Credential for using username/passwords so you're not writing them in plain text.

Related Topic