Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy file remotely with PowerShell

I am writing a PowerShell script that I want to run from Server A. I want to connect to Server B and copy a file to Server A as a backup.

If that can't be done then I would like to connect to Server B from Server A and copy a file to another directory in Server B.

I see the Copy-Item command, but I don't see how to give it a computer name.

I would have thought I could do something like

Copy-Item -ComputerName ServerB -Path C:\Programs\temp\test.txt -Destination (not sure how it would know to use ServerB or ServerA)

How can I do this?

like image 882
chobo2 Avatar asked Oct 06 '22 05:10

chobo2


1 Answers

From PowerShell version 5 onwards (included in Windows Server 2016, downloadable as part of WMF 5 for earlier versions), this is possible with remoting. The benefit of this is that it works even if, for whatever reason, you can't access shares.

For this to work, the local session where copying is initiated must have PowerShell 5 or higher installed. The remote session does not need to have PowerShell 5 installed -- it works with PowerShell versions as low as 2, and Windows Server versions as low as 2008 R2.[1]

From server A, create a session to server B:

$b = New-PSSession B

And then, still from A:

Copy-Item -FromSession $b C:\Programs\temp\test.txt -Destination C:\Programs\temp\test.txt

Copying items to B is done with -ToSession. Note that local paths are used in both cases; you have to keep track of what server you're on.


[1]: when copying from or to a remote server that only has PowerShell 2, beware of this bug in PowerShell 5.1, which at the time of writing means recursive file copying doesn't work with -ToSession, an apparently copying doesn't work at all with -FromSession.

like image 112
Jeroen Mostert Avatar answered Oct 07 '22 17:10

Jeroen Mostert