Mathias Colpaert Mathias Colpaert - 1 year ago 229
PowerShell Question

powershell copy files on remote

I am using powershell to copy files to a remote server

Copy-Item $localDir \\serverA\deploy -recurse

After, I want to make a local copy on the remote server

Copy-Item \\serverA\deploy \\serverA\production

How can I execute this last command on the server, in order to speed up copy time?

Answer Source

You can use Invoke-Command and Get-Credential to perform a command on the remote computer.

Invoke-Command -ComputerName "ServerA" -Credential (Get-Credential) -ScriptBlock {Copy-Item C:\deploy C:\production} -Authentication Kerberos

If you want to keep the session open for longer so that use can use it more that once, you can use New-PSSession.

# Setup Session with Credentials 
$Creds= Get-Credential -UserName "Domain\Username" -Message "Enter Password"
$psSession = New-PSSession -ComputerName "ServerA" -Credential $Creds -Authentication Kerberos 

# Run a command
Invoke-Command -Session $psSession -ScriptBlock {Copy-Item \\serverA\deploy \\serverA\production}
# Run another command later
Invoke-Command -Session $psSession -ScriptBlock {<#Another command later on...#>}

Use the following to pass in parameters to the session.

Invoke-Command -Session $psSession -ArgumentList @($serverPath1,$serverPath2) -ScriptBlock {
    Copy-Item $serverPath1 $serverPath2

Make sure you close the connection after use with the following

Get-PSSession | Remove-PSSession

Note: You will need to make your WinRM is configured and running on the server for remote management. You can run a quick config with the command (winrm qc).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download