Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Get Files via FTP and an Azure Function App
# FTP Variables via Function Application Settings Variables
# Username and Password
$username = $env:FTPUsername
$pwd = $env:FTPPwd
$password = ConvertTo-SecureString $pwd -AsPlainText -Force
$credentials = new-object System.Management.Automation.PSCredential($username, $password)
# Output Directory
$target = $env:FTPTargetDirectory
# Create a folder with the current date and time
$foldername = Get-Date -format dd-MM-yyyy-hh-mm;
$outputfilepath = "$target\$foldername";
# Remote Powershell Variables
# Username for connection to MIM Service via Function Application Settings
$MIMUsername = $env:MIMSyncCredUser
# Password for connection to MIM Service via Function Application Settings
$MIMpwd = $env:MIMSyncCredPassword
# Credentials password (encrypted)
$keypath = 'D:\home\site\wwwroot\MyAzureFunctionApp\keys\MIMSync.key'
$MIMpassword = $MIMpwd | ConvertTo-SecureString -key (Get-Content $keypath)
# Create PS Creds
$RPScredentials = New-Object System.Management.Automation.PSCredential $MIMUsername,$MIMpassword
# Remote Powershell Options. As we're using a self-signed cert skip CA checks
$options = New-PsSessionOption –SkipCACheck -SkipCNCheck
# Setup scriptblock
# The script that will be executed on the target server
$scriptblock = {
# allow import of the PSFTP Module
Set-ExecutionPolicy -ExecutionPolicy Bypass -Force
# Import the PSFTP Module
import-module psftp -Force -PassThru
# Create the directory for the files to go into
if(!(Test-Path $outputfpath)){
$FTPReceiveFolder = New-Item -Path $outputfpath -Type Directory ;
# Connect to FTP Server
Set-FTPConnection -Credentials $ftpcreds -Server $ftpserver -Session FTPSession -UsePassive ;
$Session = Get-FTPConnection -Session FTPSession ;
# Get first set of files
Get-FTPChildItem -Session $Session -Path $source -Filter DailyFilesApp1_* | Receive-FTPItem -Session $Session -LocalPath $outputfpath -Overwrite ;
# Get second set of Files
Get-FTPChildItem -Session $Session -Path $source -Filter NightlyExportApp2* | Receive-FTPItem -Session $Session -LocalPath $outputfpath -Overwrite;
# Close Session
Get-Variable | Where-Object Value -is [System.Net.FtpWebRequest] | Remove-Variable -Confirm:$false
# Connect to MIM Sync Server via RPS and execute our script block above passing in the necessary variables
$results = Invoke-Command $scriptblock -computer -useSSL -credential $RPScredentials -SessionOption $options -argumentlist $outputfilepath,$credentials,$env:FTPServer,$env:FTPSourceDirectory
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.