PowerShell - How to copy a local file to remote machines

During a training, a student asked me how to copy a local file to remote machines without using fileshare. It was a great question, so I decided to share here in this post.

As I need a file to be used as example, I can create a new one using the following command:

New-Item -Path C:\temp\localfile.txt -Value $env:ComputerName

The command to copy a file locally is:

Copy-Item -Path c:\temp\localfile.txt -Destination c:\localfile.txt

Now, imagine that I want to copy this file to other servers. If you are using the PowerShell 5.0, now the Copy-Item command supports copying files from one machine to another through -ToSession and -FromSession parameters. As the name suggests, the -ToSession parameter expects a session with the destination computer where the file will be copied.To create the session, I used the following command:

$Session = New-PSSession -ComputerName PowerShellAzureMachine -Credential $cred

Now we have the session, the second step is to perform the file copy via -ToSession parameter:

Copy-Item -Path C:\temp\localfile.txt -Destination C:\localfile.txt -ToSession $session

For earlier versions of PowerShell, one way of doing this is through the Invoke-Command command.

The first step is to perform the reading of the local file to a local variable:

$File = [System.IO.File]::ReadAllBytes("C:\temp\localfile.txt")

Now I use the Invoke-Command to run the copy:

Invoke-Command -Session $session -ArgumentList $file -ScriptBlock{[System.IO.File]::WriteAllBytes("C:\localfile2.txt", $args)}


I hope you have enjoyed.