With the use of this tip, you should be able to pick a particular file using its name. This same file can be pulled out from the remote server to the local path. You would also learn smart way of doing this using a for-loop. It will also show you how to use WinSCP as protocol in the 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 the HostKey
, 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 "
}
$transferOptions = New-Object WinSCP.TransferOptions
$transferOptions.ResumeSupport.State = [WinSCP.TransferResumeSupportState]::off
try
{
$session = New-Object WinSCP.Session
$session.SessionLogPath = "C:\log\logfile.log"
$session.Open($sessionOptions)
$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