Copy File To Remote Computer In PowerShell

PowerShell provides the Copy-Item file that is used to copy files. It can be also used to copy files to the remote computers too. But a session to the remote computer should be accomplished and provided to the Copy-Item command. In this tutorial, we examine how to copy single or multiple files to a remote computer.

Create Session To The Remote Computer

In order to copy files to the remote computer, a session should be established with the remote computer. the session creation requires the user name and credentials for the remote computer. The New-PSSession command is used to create a PowerShell session with the remote computer. The creation session handle is assigned to a variable and can be used by the Copy-Item command.

PS> $Session = New-PSSession -Computer 192.168.1.10 -Credential "WindowsTect\ismail.baydan"

Copy Single Files To The Remote Computer

A single file can be copied to the remote computer by using created session. The source and destination files can be specified below. The session variable is provided with the -ToSession option.

PS> $Session = New-PSSession -Computer 192.168.1.10 -Credential "WindowsTect\ismail.baydan"
PS> Copy-Item  -Path "c:\db.txt" -Destination "d:\backup\" -ToSession $Session

Copy Multiple Files To The Remote Computer

We can also copy multiple files to the remote computer. As always first we will use the New-PSSession command to create a session and then specify the source with the glob operator. The * glob operator is used to express all files for the specified path. In the following example, we copy all files located inside the C:\backup to the remote computer.

PS> $Session = New-PSSession -Computer 192.168.1.10 -Credential "WindowsTect\ismail.baydan"
PS> Copy-Item  -Path "c:\backup\*" -Destination "d:\backup\" -ToSession $Session

Copy Specified Extension Files To The Remote Computer

We can also copy files with specific extensions to the remote computer. It is very similar to the previous examples where we specify the extension we want to copy using the -Include options. In the following example, we copy files with the *.log extension.

PS> $Session = New-PSSession -Computer 192.168.1.10 -Credential "WindowsTect\ismail.baydan"
PS> Copy-Item -Include "*.log"  -Path "c:\backup\*" -Destination "d:\backup\" -ToSession $Session

Leave a Comment