Automated FTP Operations from PowerShell 7 using WinSCP .NET Assembly and WinSCP PowerShell Module.

This is the simplest method of automating ftp operations from PowerShell that I can come up with, having explored MANY incredibly convoluted alternatives.

It is an absolute minimum viable product that can be built upon, consisting of two downloadables that compliment one another and eight commands that probably do everything you need, and do it in a single command.

A link to the wiki for all the cmdlets is given in step 10 below.

Once the WinSCP module is installed, interfacing with an FTP server is as easy as this…
CerberusFTP Server displaying the inbound session from PowerShell using WinSCP cmdlets that call WinSCP .NET Assembly winSCPnet.dll
Don’t forget to close the ftp session when you’re done….
….and the session disappears from Cerberus FTP Server.

0. Download Software

Download matching versions of the Assembly and Cmdlets (5.17.10.0). The most recent version of the Automation .NET Assembly is 5.19.6.0 but you may have issues talking to WinSCP 5.19.6.0 using version 5.17.10.0 Cmdlets such as New-WinSCPSession where it complains about the winscp.exe version not matching the winscpnet.dll version.

WinSCP Automation .NET Assembly

https://sourceforge.net/projects/winscp/files/WinSCP/5.17.10/

WinSCP PowerShell Cmdlets (PowerShell Module)

https://github.com/dotps1/WinSCP/releases/download/WinSCP-PowerShell-v5.17.10.0/WinSCP.zip

1. Install WinSCP FTP Module in PowerShell 7

Install-Module -Name WinSCP
Import-Module -Name WinSCP
Add-Type -Path "WinSCPnet.dll"

2. Create encrypted credentials .xml file for use when connecting to ftp server automatically

$credential = Get-Credential
$credential | Export-Clixml ftpcredentials.xml
$ftpcredentials = Import-Clixml ftpcredentials.xml

3. Establish a session with an FTP Server

$ftpsessionoptions = New-WinSCPSessionOption -Credential $ftpcredentials -HostName "ftp.cyberfella.co.uk" -Protocol ftp

New-WinSCPSession -SessionOption $ftpsessionoptions

4. See if a file exists on the ftp server

Test-WinSCPPath -Path "/*.done"         


                False

5. Receive a file

Receive-WinSCPItem -RemotePath /ftptest.txt


                   Destination: C:\Users\matt\Documents\WindowsPowerShell\My Code

                IsSuccess FileName
                --------- --------
                True      ftptest.txt

6. Send a file

 Send-WinSCPItem -LocalPath "ftptest.txt"


                   Destination: \

                IsSuccess FileName
                --------- --------
                True      ftptest.txt

7. Send a folder and its entire contents (recursive by default)

Send-WinSCPItem -LocalPath "FTPTest"


                   Destination: \FTPTest

                IsSuccess FileName
                --------- --------
                True      {FTP-Functions-MB.ps1, ftptest.txt, ListFTP-MB.ps1}

8. Receive a folder and its entire contents (recursive by default)

Receive-WinSCPItem -RemotePath /FTPTest


                   Destination: C:\Users\matt\Documents\WindowsPowerShell\My Code\FTPTest

                IsSuccess FileName
                --------- --------
                True      {FTP-Functions-MB.ps1, ListFTP-MB.ps1, ftptest.txt}

9. Close Session to FTP Server

Remove-WinSCPSession

10. Wiki doc for all cmdlets here

https://github.com/dotps1/WinSCP/wiki

Additional commands required for Secure FTP (SSH Hostkey Fingerprint)

The example above was kept as simple as possible to demonstrate the minimum number of steps in order to “get things working”. Now we can build upon those steps and establish an sftp connection to the FTP Server.

Additional commands to set up an sftp session

Import-Module -Name WinSCP
Add-Type -Path "WinSCPnet.dll"

$ftpcredentials = Import-Clixml ftpcredentials.xml

$ftpsessionoptions = New-WinSCPSessionOption -Credential $ftpcredentials -HostName "10.0.2.15" -Protocol sftp

$sshHostKeyFingerprint = Get-WinSCPHostKeyFingerprint -SessionOption $ftpsessionoptions -Algorithm SHA-256

$ftpsessionoptions.SshHostKeyFingerprint = $sshHostKeyFingerprint

New-WinSCPSession -SessionOption $ftpsessionoptions

Cerberus FTP Server showing the sftp connection

Send-WinSCPItem -LocalPath "FTPTest"

Cerberus FTP Server Log entries showing the connection and the recursive transfer of a folder containing multiple files.

Receive-WinSCPItem -RemotePath /FTPTest

Recursively downloading a folder containing multiple files over sftp

Remove-WinSCPSession

The session disappears from Cerberus

My Powershell Code

# Pre-requisites
# EXECUTION POLICY SET TO BYPASS (TEST ENV)
# https://docs.microsoft.com/en-gb/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-7.2
# Set-ExecutionPolicy -ExecutionPolicy ByPass

# WinSCP Automation .NET Assembly
# https://winscp.net/download/WinSCP-5.19.6-Automation.zip    #WINSCP AUTOMATION .NET LIBRARY DLL
# https://winscp.net/eng/docs/library_powershell#example      #NOTES ON INSTALLATION OF DLL
# https://dotps1.github.io/WinSCP/                            #WINSCP CMDLETS MODULE

# Install (Run PowerShell as Administrator)
# Install-Module -Name WinSCP

# Import Module
Import-Module -Name WinSCP

# Cmdlets
# Get-Command -Module WinSCP

# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"

#Create Credential
#Set credentials to a PSCredential Object.
#$credential = Get-Credential
#Export credential to xml file
#$credential | Export-Clixml ftpcredentials.xml
#Import credential from xml file
$ftpcredentials = Import-Clixml ftpcredentials.xml

#VARIABLES SECTION
$ftphost="10.0.2.15"
$ftproot="/"
$ftpdirectory="FTPTest/"
$SendItem = $ftpdirectory + ""
$ReceiveItem = $ftpdirectory + ""
$FileFilter = "*"
#END OF VARIABLES SECTION

#FUNCTIONS SECTION
function Connect-FTP {
    #Connects using sftp to ftp server
    Write-Host "Connecting to FTP Server $ftphost..."
    $ftpsessionoptions = New-WinSCPSessionOption -Credential $ftpcredentials -HostName $ftphost -Protocol sftp
    $sshHostKeyFingerprint = Get-WinSCPHostKeyFingerprint -SessionOption $ftpsessionoptions -Algorithm SHA-256
    $ftpsessionoptions.SshHostKeyFingerprint = $sshHostKeyFingerprint
    New-WinSCPSession -SessionOption $ftpsessionoptions
    Write-Host "Connected Successfully to FTP Server $ftphost."
}
function Disconnect-FTP {
    #Disconnects session to ftp server
    Write-Host "Disconnecting from FTP Server $ftphost..."
    Remove-WinSCPSession
    Write-Host "Disconnected."
}
function List-FTP {
    #Gets a list of the files matching the filter in the specified ftp directory only (1 level)
    Connect-FTP
    Write-Host "Listing files in $ftpdirectory..."
    $fileitems = Get-WinSCPChildItem -Path $ftproot$ftpdirectory -Depth 1 -File -Filter $FileFilter
    Disconnect-FTP
}   
function Send-FTP {
    #Sends a specified local file or recursive directory's contents to ftp server
    Connect-FTP
    Write-Host "Sending everything in $SendItem to $ftphost..."
    Send-WinSCPItem -LocalPath $SendItem
    Write-Host "Finished sending."
    Disconnect-FTP
}
function Receive-FTP {
    #Receives a specified remote file or directory on the ftp server recursively by default
    Connect-FTP
    Write-Host "Receiving file(s) in $ReceiveItem from $ftphost..."
    $fileitems = Receive-WinSCPItem -RemotePath $ReceiveItem
    Write-Host "Finished receiving."
    Disconnect-FTP
}
#END OF FUNCTIONS SECTION

#MAIN CODE
List-FTP
Receive-FTP
Send-FTP
#END OF MAIN CODE
Executing the script above to list files on an ftp server over sftp, download a folder and upload a folder
Facebooktwitterredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.