Copy file remotely with PowerShell
Simply use the administrative shares to copy files between systems. It's much easier this way.
Copy-Item -Path \\serverb\c$\programs\temp\test.txt -Destination \\servera\c$\programs\temp\test.txt;
By using UNC paths instead of local filesystem paths, you help to ensure that your script is executable from any client system with access to those UNC paths. If you use local filesystem paths, then you are cornering yourself into running the script on a specific computer.
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
.