Bootstrap FreeKB - PowerShell - Upload or Download files between remote servers using Copy-Item and PSSession
PowerShell - Upload or Download files between remote servers using Copy-Item and PSSession

Updated:   |  PowerShell articles

Typically, Copy-Item is used to copy a file from one directory to another directory on the same system. In this example, the example.txt file will be copied from the C:\Users\JohnDoe\foo directory to the C:\Users\JohnDoe\bar directory.

Copy-Item -Path C:\Users\JohnDoe\foo\example.txt C:\Users\JohnDoe\bar

 

New-PSSession can be used to make a Remote Connection to a Windows servers.

$pssession = New-PSSession -ComputerName server1.example.com -Credential JohnDoe

 

The Get-PSSession command should now return something like this.

 Id Name      ComputerName         ComputerType    State         ConfigurationName     Availability
 -- ----      ------------         ------------    -----         -----------------     ------------
  1 WinRM1    server1.example.com  RemoteMachine   Opened        Microsoft.PowerShell     Available

 

Then Copy-Item can be used to upload or download files between your local PC and the remote Windows system. In this example, the example.txt file will be uploaded from C:\Users\JohnDoe\example.txt on the local PC to C:\Temp on server1.

Copy-Item -Path C:\Users\JohnDoe\example.txt -ToSession $pssession -Destination C:\Temp

 

In this example, the example.txt file will be downloaded from C:\Temp\example.txt on server1 to C:\Users\JohnDoe\example.txt on the local PC

Copy-Item -FromSession $pssession C:\Temp -Destination C:\Users\JohnDoe\example.txt

 

It's probably a good idea to use a try catch finally block to catch any exceptions that are raised.

try {
    $pssession = New-PSSession -ComputerName server1.example.com -Credential JohnDoe
}
catch {
    Write-Warning $Error[0]
}

try {
    Copy-Item -Path C:\Users\JohnDoe\example.txt -ToSession $pssession -Destination C:\Temp
}
catch {
    Write-Warning $Error[0]
}

 

Last but not least, remove the PSSession.

Remove-PSSession -InstanceId $pssession.InstanceId

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter ba08bd in the box below so that we can be sure you are a human.