Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Command to Copy File on Remote Machine

Tags:

powershell

I have a requirement to copy file from local machine to remote machine using PowerShell. I can copy the file to remote computer using following command:

copy-item -Path d:\Shared\test.txt -Destination \\server1\Shared

the above command uses network share path to copy the file. I don't want to use network share option as the folder will not be shared on the remote machine. I tried following commands but not working.

copy-item -Path d:\Shared\test.txt -Destination \\server1\c$\Shared

Invoke-Command -ComputerName \\server -ScriptBlock {
  copy-item -Path D:\Shared\test.txt -Destination C:\Shared
}

Please let me know how to make it working without using UNC path. I have full permissions on that folder on the remote machine.

like image 496
Parveen Kumar Avatar asked Dec 31 '14 10:12

Parveen Kumar


2 Answers

Powershell 5 (Windows Server 2016)

Also downloadable for earlier versions of Windows. -ToSession can also be used.

$b = New-PSSession B
Copy-Item -FromSession $b C:\Programs\temp\test.txt -Destination C:\Programs\temp\test.txt

Earlier versions of PowerShell

Does not require anything special, these hidden shares exist on all machines.

Copy-Item -Path \\serverb\c$\programs\temp\test.txt -Destination \\servera\c$\programs\temp\test.txt
like image 180
Mikael Dúi Bolinder Avatar answered Oct 23 '22 04:10

Mikael Dúi Bolinder


If there is not an accessible share, you'll have to make the file content itself an argument to the script:

Invoke-Command -ComputerName \\server -ScriptBlock {
  $args[0] | Set-Content  C:\Shared\test.txt
  } -ArgumentList (Get-Content D:\Shared\test.txt -Raw) 
like image 40
mjolinor Avatar answered Oct 23 '22 04:10

mjolinor