Copy files to remote computers

I want to copy a file to several servers. I’m using a
text file Srv.txt containing the servernames:

$Dist = Get-Content -path D:\Scripts\Dist\Srv.txt

ForEach ($i in $Dist){
Copy-Item -path D:\Scripts\Dist\C.txt -Destination \$dist\D$\Scripts

When I run this script I get this error message:

Copy-Item : The network name cannot be found.

At D:\Scripts\Dist\DistTS.ps1:14 char:10

  • Copy-Item <<<< -path D:\Scripts\Dist\C.txt -Destination \$dist\D$\Scripts\
    • CategoryInfo : NotSpecified: (:slight_smile: [Copy-Item], IOException
    • FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.CopyItemCommand

When I use Copy-Item -path D:\Scripts\Dist\C.txt -Destination \Srv1\D$\Scripts
the file is copied.

Copy-Item -path D:\Scripts\Dist\C.txt -Destination \$dist\D$\Scripts\

Your syntax is wrong you should have \$i\D$$scripts after -Destination

because remember your now looking foreach therefore individual but instead you have done the both servers


exactly, thanks that was it cheers

Rashid is right, you need to use $i instead of $Dist inside the ForEach loop, otherwise the resulting command would look like:

Copy-Item -path D:\Scripts\Dist\C.txt -Destination \\Srv1 Srv2 Srv3\D$\Scripts

Another thing that may cause this script to fail is if the administrative shares are not available (this is not likely the case here since your manual command works). They are not available by default in Server 2012 R2. To enable them you need to enable File and Print sharing as in:

netsh advfirewall firewall set rule group=”File and Printer Sharing” new enable=Yes

Couple of additional observations:

  • Try to use variable names that reflect the variable content. It helps the reader to quickly recognize what the variable content is. For example, I would use
    $Server as variable name instead of $i in the ForEach loop
  • Try to use quotes around your parameters. This helps the code to not break when one of the variables in the parameters has a space for example.
    So, I would use "\$dist\D$\Scripts" instead of \$dist\D$\Scripts\