Upload Files to SFTP via Powershell

Hello everyone.

I was asked how to upload files to SFTP from Business Central, there are several ways to do it and several posts published about it for Business Central.

In this case, without going through other Azure services, PowerApps etc., it is possible to do it directly and simply via Powershell and, given that the previous post on Powershell was quite successful, I also report this functionality in the blog.

It’s not like everything has to be developed always within Business Central.

In this case we rely on a ready-made OpenSource library (WinSCP) that will take care of the SFTP calls.

The Powershell script can be scheduled via Windows Task Scheduler, just assign them sufficient permissions to execute the scripts.

Download & Install WinSCP

WinSCP :: Official Site :: Free SFTP and FTP client for Windows

We will use the WinSCPnet.dll, installed by WinSCP, which exposes this directive for SFTP

[WinSCP.Protocol]::Sftp

WinSCP

Pwshell Script

#RUN POWERSHELL WITH UNRESTRICTED POLICY

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Verbose

#Load Assembly .NET WinSCP (DLL in windows\system32)

Add-Type -Path “WinSCPnet.dll”

#Set session options

$sessionOptions = New-Object WinSCP.SessionOptions -Property @{

#Protocol User, Pws, Target server, connection info

Protocol = [WinSCP.Protocol]::Sftp   #declare SFTP protocol

HostName = “HostName”

PortNumber = 2229

UserName = “username”

Password = “password”

  #Authorization SshHostKeyFingerprint – KEY 2048 encryption

SshHostKeyFingerprint = “ssh-rsa 2048 XXXXXXX/XXXXXXXXXXXXXXXXXXX”

}

#Activate WinSCP SFTP session

$session = New-Object WinSCP.Session   #WINSCP

#GO

try

{

# Open Connection

$session.Open($sessionOptions)

# File Transfer – default over-write

$session.PutFiles(“C:\SOURCE_FOLDER\*.*”, “/TARGET_FOLDER/*”).Check()

}

finally

{

$session.Dispose()

}

Old post

Export SQL data to CSV or XML File via Powershell – Roberto Stefanetti – MVP and MCT Business Central (robertostefanettinavblog.com)

Leave a Reply

Your email address will not be published.

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