Copy file to multiple remote servers

 I often have to copy files and folders from one server to another for various reasons. Copying stuff manually is a bore but if you are only copying to a couple of servers it is quicker to do it manually but if you have to copy to several servers it would be quicker to use a script. We can leverage PowerShell to perform this task.

We will use the Copy-Item cmdlet in PowerShell. It will copy file and folders to a remote server using the following syntax:

Copy-Item “source” -Destination “\\server\C$”

To make it a little but more sophisticated we will add a check to confirm that the remote servers’ path exists using the Test-Path cmdlet before performing the copy. If the path does not exist it will state that it “is not reachable or does not exist”:

# This file contains the list of servers you want to copy files/folders to
$computers = gc “C:\scripts\servers.txt”

# This is the file/folder(s) you want to copy to the servers in the $computer variable
$source = “C:\Software\EMC\Networker\NWVSS.exe”

# The destination location you want the file/folder(s) to be copied to
$destination = “C$\temp\”

foreach ($computer in $computers) {
if ((Test-Path -Path \\$computer\$destination)) {
Copy-Item $source -Destination \\$computer\$destination -Recurse
} else {
“\\$computer\$destination is not reachable or does not exist”
}
}
 

OR

#Point the script to the text file
$Computers = Read-Host “Enter Location Of TXT File”
# sets the varible for the file location ei c:\temp\ThisFile.exe
$Source = Read-Host “Enter File Source”
# sets the varible for the file destination
$Destination = Read-Host “Enter File destination (windows\temp)”
# displays the computer names on screen
Get-Content $Computers | foreach {Copy-Item $Source -Destination \\$_\c$\$Destination

OR

$a = Get-Content “D:\Scripting\Srvlist.txt”
foreach ($i in $a)
{$files= get-content “D:\Scripting\filelist.txt”
foreach ($file in $files)
{Copy-Item $file -Destination \\$i\C$\temp -force}
}

Leave a Reply

Your email address will not be published. Required fields are marked *