Using foreach to copy a file over to multiple servers within a CSV file

Hello,

I am trying to copy an MSI over to multiple servers that are listed in a CSV file and I seem to have an issue with the network location not working. My PowerShell script at the moment looks like this.

#List of servers names in CSV format
$servers = Import-Csv "C:\Users\%username%\Desktop\servers.csv"

#Locations for copying
$source = "\\server1\software$\app1.msi"
$destination = "c$\windows\temp"

#Copy App1 Installation File to Server
foreach ($server in $servers){
    Copy-Item $source -Destination \\$server\$destination -Recurse -Force
}

It seems to say that it cannot find the network location, but the UNC path is correct, clearly, I am doing something wrong. Any pointers in the right direction?

You know that dollar sign $ in PowerShell is used to access variable right?

So from example:

"\\server1\software$\app1.msi"

PowerShell means that you’re talking about variable named $\app1 and then accessing it’s member called msi

See?

Use single quotes instead of double quotes to assign UNC path.

1 Like

Hi Metablaster,

Thanks, tried that and still getting the same error, saying network location not found, even though both source and destination locations are correct.

Since I am running the command on the server which has the source files I changed it to ‘c:\software\app1.msi’ and still get the same error.

I think it’s the destination it’s struggling with, rather than the source, but cannot understand why it’s failing.

Figured it out, so because my CSV file has a header for the column I had to include that into my script.

For example, my header for the column in the CSV file was ServerName so my script looks like this.

#A list of server names in CSV format
$servers = Import-Csv "C:\Users\%username%\Desktop\servers.csv"

#Locations for copying
$source = 'M:\software\app1.msi'
$destination = 'c$\windows\temp\'

#Copy App1 Installation File to Server
foreach ($server in $servers.ServerName){
    Copy-Item $source -Destination \\$server\$destination -Recurse -Force -Verbose
}

This has copied the files over to both servers within my CSV file.

1 Like

Nice, thanks for feedback, because I was testing here and it worked fine without any quotes.

forum formatting made me think single quotes are needed.