Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / containers / virtual-machine

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.00/5 (No votes)
8 Jun 2023CPOL1 min read 9.3K   21  
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.
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

  1. Paste the code into Notepad.
  2. Save the file in ps1 file type. This refers to PowerShell.
  3. Update the string to the right ones.
  4. 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.
  5. 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.
PowerShell
 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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)