Copy files to remote computers

Tagged: ,

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Sam Boutros Sam Boutros 2 years, 4 months ago.

  • Author
    Posts
  • #17676
    Profile photo of breeks
    breeks
    Participant

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

    $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: (:) [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.

  • #17680
    Profile photo of Adnan Rashid
    Adnan Rashid
    Participant

    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

    cheers

  • #17681
    Profile photo of breeks
    breeks
    Participant

    exactly, thanks that was it cheers

  • #17683
    Profile photo of Sam Boutros
    Sam Boutros
    Participant

    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\

You must be logged in to reply to this topic.