How to Copy File to Remote Computer Using PowerShell

Problem

In this blog post, we will walk you through how to copy file to remote computer using PowerShell.

Solution

To connect to remote computer, we must create a session and store it into a variable. Then, the variable will be used by Copy-Item cmdlet to copy the file to the destination.

In this context, we have two computers named vm1 and vm2 respectively. The client will be vm1 and we will copy (transfer) the file from vm1 to vm2 machine.

Since the computers are not in the same domain, we should use Windows Remote Management (WinRM) for remote communication or remoting.

Below are several prerequisites to use WinRM for remote communication:

  1. Enable Windows Remote Management (WinRM) service on both computers

Set-Service -Name WinRM -Status Running -StartupType Automatic

  1. Add servers we want to connect to TrustedHosts list on client computer

Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value 'vm2'

  1. Enable firewall rule for WinRM to allow other IPs to connect

Set-NetFirewallRule -Name 'WINRM-HTTP-In-TCP' -RemoteAddress Any
Enable-NetFirewallRule -Name 'WINRM-HTTP-In-TCP'

Or you can also do it manually:

1. Open Windows Defender Firewall with Advanced Security
2. Click Inbound Rules
3. Double-click Windows Remote Management (HTTP-In) for the Public profile
4. Click the Scope tab
5. Under Remote IP address, set it to `Any IP Address`
6. Enable Rule
Set-NetFirewallRule -Name 'WINRM-HTTP-In-TCP' -RemoteAddress Any Enable firewall rule for Windows Remote Management (HTTP-In)

Using Enter-PSSession cmdlet

Firstly, we need to create a session and store it into a variable.


$Session = New-PSSession -ComputerName "vm2" -Credential (Get-Credential)

create pssession and store it to a variable

Then we will copy the file using Copy-Item cmdlet. The destination folder must exist in remote computer. Otherwise, there will be an error. We also use session variable declared previously.


Copy-Item 'C:\Scripts\test.ps1' -Destination 'C:\Scripts_Copy\' -ToSession $Session

result after copying file to remote computer

Conclusion

To copy file to remote computer, we need to establish connection to remote computer (remoting) and store it into a variable that later will be used by Copy-Item to copy file to the destination.