
Automate FTP with PowerShell
So, you want to Automate FTP with PowerShell? Well, you have come to the right place. FTP is not dead . In fact, it is still quite widely used. If all you need is files to be transferred from one place to another, it is the best choice.
Why would you need to Automate FTP with PowerShell
There are several reasons you would need to automate FTP with PowerShell. One is compatibility. Batch files are still around but to get them to automate FTP, you must call on third party programs that may or may not be kept up to date. As OSes start to update the third party application may fall behind. This leads me to my second point….
Security with PowerShell
You can be more granular with security and PowerShell. It is baked into M365 and local AD so you can be sure that only the users you require can run the script to Automate FTP with PowerShell.
Prerequisites to the Script
You will need the following before you can run the script to Automate FTP with PowerShell.
WinSCP Automation
The script calls on WinSCP FTP Automation to load a DLL so it can connect to your required FTP Server and transfer files. You need to register the DLL in the Directory it is going to be called from. The documentation is a bit confusing but simply put, extract the DLL to the same folder as the script. Then drop to CMD prompt and navigate to that folder and then register the DLL:
%WINDIR%\Microsoft.NET\Framework64\<version>\RegAsm.exe WinSCPnet.dll /codebase /tlb Make sure the version of .NET you are using is specified in <version>. I used v4.0.30319
So, my command looked like this:
%WINDIR%\Microsoft.NET\Framework64 v4.0.30319\RegAsm.exe WinSCPnet.dll /codebase /tlb If Running the Script on a Server
You need to make sure the Above DLL is registered for the user account running the script. You also need Full Control file security on the folder that houses the script. The reason for this is you need to be able to rename and move files in and around the file structure which otherwise require admin access. Without this, the script will not run.
If Connecting to SFTP
You will need to get the SSHHost Key If connecting with a password or both the SSHHost Key and SSHKeyPath file (if not using a password) and point to where it is stored (Preferable in the same folder as everything else).
But if you connect manually to these servers, you already have this information. If not, reach out to the vendor or organization you need to connect to. My example only needs the SSH Host Key.
Bonus: If You Plan to Notify of Completion or Errors via Email
If you plan To Send Mail In PowerShell , you will need to create an App Registration in Entra with the correct permission to send mail and then have that account give consent to allow it to be used to send mail through API (like PowerShell). I have written an article about it. You should check it out. It will help Automate FTP with PowerShell.
The Script
This is an example of a PowerShell Script to Automate FTP with PowerShell by downloading a file, renaming it and then moving it:
try
{
# Load WinSCP .NET assembly
Add-Type -Path “C:\Path\To\WinSCP\Automation\WinSCPnet.dll” ## https://winscp.net/download/WinSCP-5.19.6-Automation.zip
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp # Port 22 Sftp | FTP Port: 21
HostName = “<ip address>” #IP TO FTP/SFTP
UserName = “<username>” #USERNAME
Password = <password>!” #PASSWORD LEAVE EMPTY IF YOU USE PRIVATE KEY LIKE THIS( Password = “” )
SshHostKeyFingerprint = “ssh-ed25519 255 UINj1Jc5jKcADtEwF0dd0tUjjk4KNp3JN6EyQf5G7ns”
#SshPrivateKeyPath= “C:\Users\Admin\private.ppk” #If you use password make “SshPrivateKeyPath” to a comment or delete the line!
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
$transferOptions = New-Object WinSCP.TransferOptions
$transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
$transferResult =
$session.GetFiles(“/incoming/Sample.csv”, “C:\Path\To\File\Upload\”, $False, $transferOptions) #Get files from incoming to upload
# Use $session.PutFiles(LocalPath, RemotePath) instead If you are wanting to send files to the SFTP/FTP Server.
# Throw on any error
$transferResult.Check()
# Print results
foreach ($transfer in $transferResult.Transfers)
{
Write-Host “Download of $($transfer.FileName) to $localPath succeeded”
$transferResult.Transfers
}
}
finally
{
# Disconnect, clean up (Session.Close to exit the session!)
$session.Close()
}
#exit 0
}
catch
{
Write-Host “Error: $($_.Exception.Message)”
.\NotifyMailFailed.ps1
exit 1
}
$Exist = Test-Path “C:\Path\To\File\Upload\”, Sample.csv” -PathType Leaf
$IsTrue = $Exist
if ($IsTrue) {
# rename file and move to Archive Folder
# Write file is there
$time = Get-Date -Format “MM-dd-yyyy”
Rename-Item -Path ” C:\Path\To\File\Upload\Sample.csv” -NewName Sample_$time.CSV
Move-Item -Path ” C:\Path\To\File\Upload\*.csv” -Destination ” C:\Path\To\File\Upload\saved”
## Notifying Via Email Upload is Complete
#refer to https://quickm365tips.com/the-correct-way-to-send-mail-in-powershell/
.\NotifyMail.ps1
} else {
# Write file is NOT there
## Notifying Via Email Upload is Complete
#refer to https://quickm365tips.com/the-correct-way-to-send-mail-in-powershell/
.\NotifyMailFailed.ps1
}
Benefits When You Automate FTP with PowerShell
When you can automate any process that is normally done manually, it is a benefit. It saves you time from performing several steps and concentrates on what you need to do most. Probably analyzing the data (Not retrieving it)!
Another Benefit is if you must automate several FTP services all you have to do is copy the script and change the particulars. You will be up and running in no time 😊
