How to interactive with SFTP via PowerShell (Download/Upload)

Using Posh-SSH module as example

LAI TOCA
2 min readAug 16, 2023
Photo from : https://www.business2community.com/b2b-marketing/b2b-digital-marketing-profit-data-01959263

We got several ways to interchange B2B data, AS2/Van (EDI format), API (XML, JSON format) or FTP/SFTP (Any kind (excel, PDF, txt…) of file format). The story introduced a general RPA (Robotic Process Automation) that using PowerShell to interactive with SFTP for B2B data transformation.

First we used NUGET to install the third party library: Posh-SSH for initialize a SFTP client to remote SFTP server. We could use below commands to make sure that module installation was successfully and the PowerShell module path was setup properly.

Get-Module -ListAvailable
$Env:PSModulePath

Before we jumped into the connection with remote server. Please remember that it was a bad ideal (security concern) to store the plain text something like password or account information into the script code snippet (for the connection purpose). We could use below script to hashing your plain text into hash text:

$cred = Get-Credential
$cred | Export-Clixml -Path D:\Credential\credential.xml

So if the credential file was created and placed in target path. We could begin to write down the upload and download code sections.

Import-Module Posh-SSH

## [QAS] SFTP
$sftpPath = "ftpuat.xxx.com"

## import credentail we created from prepare steps.
$credentail = Import-Clixml -Path "D:\Credential\credential.xml"


## setup download path.
$remoteOutBoundPath= "/users/uat/Outbound/"
$destPath = "D:\SFTP\InBound\"

## connect to SFTP to download data.
$sftp = New-SFTPSession -ComputerName $sftpPath -Credential $credentail -Port 2380 -Verbose

Get-SFTPChildItem -SessionId $sftp.SessionId -Path $remoteOutBoundPath -Recursive | ForEach-Object {
Write-Ouput $_.FullName
Get-SFTPItem -SessionId $sftp.SessionId -Path $_.FullName -Destination $destPath -Force
Remove-SFTPItem -SessionId $sftp.SessionId -Path $_.FullName -Force
}
Remove-SFTPSession -SessionId $sftp.SessionId

## setup upload path.
$remoteOutBoundPath= "/users/uat/Inbound/"
$sourcePath= "D:\SFTP\OutBound\"

## connect to SFTP upload data to remote path.
$sftp = New-SFTPSession -ComputerName $sftpPath -Credential $credentail -Port 2380 -Verbose
$files = Get-ChildItem -Path $sourcePath
foreach ($file in $files) {
Set-SFTPItem -SessionId $sftp.SessionId -Destination $remoteOutBoundPath -Path $file.FullName -Force
Remove-Item -Path $file.FullName -Force
}
Remove-SFTPSession -SessionId $sftp.SessionId

Please note that the author of Posh-SSH made some breaking change for the package after V3.0, so some network resource(s) or sample(s) that used older version with older syntax/command can not apply to latest version.

Reference

--

--

LAI TOCA

Coding for fun. (Either you are running for food or running for being food.)