Using WinSCP and PowerShell Script to Copy or Move Files from a One Virtual Machine/Remote Server Path to a Path in a Local Server





0/5 (0 vote)
When you want to get files from a remote machine and needed by a system or other process, it is possible using WinSCP and PowerShell script.
Introduction
The code will help you copy files from one location to another. It is very useful as it is a secure way to move files from one remote location to another, especially when used over SFTP. It is a very secure process because a password, username and an SsHostKeyFingerprint
is required for authentication purposes.
Background
In my case, this solution has been used on a Windows machine where the WinSCP software is installed. I have also called the WinSCPnet.dll library to be referenced to the kind of connection I am using. Also note that both machines need to be turned to allow communication.
Using the Code
- Paste the code into Notepad.
- Save the file in ps1 file type. This refers to PowerShell.
- Update the
string
to the right ones. - Obtain the authentication credential from server administrator. This will include the
SshHostKey
. Once a connection is established, WinSCP is able to obtain theHostKey
, which it validates often. - You can have an automation to call this file periodically. During a call, it picks a file from the remote location to Local server. The automation can be handled using Windows task scheduler.
try
{
add-type -Path 'C:\Program Files (x86)\WinSCP\WinSCPnet.dll'
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "Host name of the Server"
PortNumber = port number
UserName = "username"
Password = "password"
SshHostKeyFingerprint = "enter SshHostKeyFingerprint string here "
}
#setup transfer options
$transferOptions = New-Object WinSCP.TransferOptions
$transferOptions.ResumeSupport.State = [WinSCP.TransferResumeSupportState]::off
try
{
# set some sessions here
$session = New-Object WinSCP.Session
$session.SessionLogPath = "C:\log\logfile.log"
$session.Open($sessionOptions)
#Folder structure
$remotePath = "/folder1/folder2"
$localPath = "C:\folder1\folder2\"
#Mask - this will filter from a folder with many other files by using the mask string
$mask = "file to search for*"
$files = $session.EnumerateRemoteFiles(
$remotePath, $mask, [WinSCP.EnumerationOptions]::AllDirectories)
foreach ($fileInfo in $files)
{
$filePath = [WinSCP.RemotePath]::EscapeFileMask($fileInfo.FullName)
$session.GetFiles($filePath, $localPath + "\*").Check()
$session.RemoveFiles($fileInfo.FullName)
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch
{
Write-Host "Error: $($_.Exception.Message)"
exit 1
}
Points of Interest
It is a very simple and a clear script to understand. I love the fact that it stands to be one correct and safe way to move files, especially when you are able to use the Mask
function.
History
- 7th June, 2023: Initial version