Copy file(s) to servers with powershell

Copying file(s) to multiple servers using windows explorer or other tools can be time consuming. There is a built-in alternative which can save you some time.

With the copy-item cmdlet you can copy a file or directory tree to a remote server when you specify a share as the destination. A small example: copying config.txt to SRV1 D:\app\config\config.txt

Copy-Item “c:\temp\config.txt” -Destination “\\SRV1\d$\app\config”

Note this assumes your current credentials suffice to perform the operation. If your current credentials do not suffice you have to use -credential to specify valid credentials.

The next step, copying from a single server to multiple servers, is quite easy.

First define a list of servers you want to copy the file to. You can put the list of servers into an array:

$SERVERS = @(“SRV1″,”SRV2″,”SRV3”)

Or you can place a list of destination servers into a text file and read that file into a variable:

$SERVERS = get-content servers.txt

Now we have a list of servers available in $SERVERS we can loop through this list with foreach and execute the copy-item cmdlet for each iteration:

$SERVERS|foreach {Copy-Item “c:\temp\config.txt” -Destination “\\$_\d$\app\config”}

With the above command we execute the copy-item cmdlet for each input item (piped from $SERVERS).  Here $_ represents the current input item which means we are actually executing:

Copy-Item “c:\temp\config.txt” -Destination “\\SRV1\d$\app\config”
Copy-Item “c:\temp\config.txt” -Destination “\\SRV2\d$\app\config”
Copy-Item “c:\temp\config.txt” -Destination “\\SRV3\d$\app\config”

You can learn more about copy-item and foreach by executing get-help foreach and get-help copy-item.