PowerShell script to download all files from FTP folder then delete files

PowerShellA few weeks ago, I did an article on making folder backups on an FTP site and compressed MySQL backups using Cron.

With the backups made, they need to be downloaded and this is not something I want to do manually. My initial thought was VBA until common sense kicked in and I opted for PowerShell. I found a post on Stack overflow which had the required script to connect to an FTP site and download files which got me half of what I needed.

I did some reading up and was able to work out the function to delete files on an FTP site and have included that in the PowerShell below so that this script both downloads files and deletes them.

There are several parameters which need to be set and these are placed at the top and highlighted to make them easy to identify; make sure all of the highlighted parts are replaced including the curly brackets.

#FTP Server Information - SET VARIABLES
$ftp = "{ftp site}"
$user = "{user}"
$pass = "{password}"
$folder = "{source folder}"
$target = "{destination folder}"

#Register get FTP Directory function
function Get-FtpDir ($url, $credentials) {
	$request = [Net.WebRequest]::Create($url)
	$request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory

	if ($credentials) { $request.Credentials = $credentials }
	
	$response = $request.GetResponse()
	$reader = New-Object IO.StreamReader $response.GetResponseStream() 
	
	while(-not $reader.EndOfStream) {
		$reader.ReadLine()
	}
	
	$reader.Close()
	$response.Close()
}

#Register Delete function
function Del-FtpFile($source, $credentials) {
    $source2 = [system.URI] $source
	
    $ftp = [System.Net.FtpWebRequest]::create($source2)
    $ftp.Credentials = $credentials

    $ftp.Method = [System.Net.WebRequestMethods+Ftp]::DeleteFile
	
    $ftp.GetResponse()
}

#Set Crednetials
$credentials = new-object System.Net.NetworkCredential($user, $pass)

#set folder path
$folderPath= $ftp + "/" + $folder + "/"

$files = Get-FTPDir -url $folderPath -credentials $credentials

$webclient = New-Object System.Net.WebClient 
$webclient.Credentials = $credentials 
$counter = 0
foreach ($file in ($files | where {$_ -like "*.gz"})){
	$source = $folderPath + $file  
	$destination = $target + $file 
	$webclient.DownloadFile($source, $destination)
	
	#PRINT FILE NAME AND COUNTER
	$counter++
	$source
	
	# DELETE FILE
	Del-FtpFile -source $source -credentials $credentials
}