Download and delete files from FTP using Powershell

The following Powershell script connects to a FTP server, gets a list of files from a specific subfolder, downloads and deletes them.

It uses the System.URI,,, System.Net.NetworkCredential, System.IO.StreamReader and other .Net classes.

$local_target1 = 'D:\997\'

function GetFilesListAsArray($user,$pass,$local_target,$ftp_uri,$subfolder)
 # ftp address from where to download the files
 $ftp_urix = $ftp_uri + $subfolder
 $uri=[system.URI] $ftp_urix


 $ftp.Credentials=New-Object System.Net.NetworkCredential($user,$pass)
 #Get a list of files in the current directory.
 #Use ListDirectoryDetails instead if you need date, size and other additional file information.

 $reader=New-Object System.IO.StreamReader($strm,'UTF-8')
 return $lines
 $_|fl * -Force

function DownloadFile ($sourceuri,$targetpath,$username,$password){
 # Create a FTPWebRequest object to handle the connection to the ftp server
 $ftprequest = [System.Net.FtpWebRequest]::create($sourceuri)

# set the request's network credentials for an authenticated connection
 $ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password)

$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
 $ftprequest.UseBinary = $true
 $ftprequest.KeepAlive = $false

# send the ftp request to the server
 $ftpresponse = $ftprequest.GetResponse()

# get a download stream from the server response
 $responsestream = $ftpresponse.GetResponseStream()

# create the target file on the local system and the download buffer
 $targetfile = New-Object IO.FileStream ($targetpath,[IO.FileMode]::Create)
 "File created: $targetpath"
 [byte[]]$readbuffer = New-Object byte[] 1024

# loop through the download stream and send the data to the target file
 $readlength = $responsestream.Read($readbuffer,0,1024)
 while ($readlength -ne 0)

 $_|fl * -Force

function DeleteFile ($file,$username,$password){
 # Delete files from FTP server after download
 $uri2=[system.URI] $file
 $request = [system.Net.FtpWebRequest]::Create($uri2)
 $request.Credentials = New-Object System.Net.NetworkCredential($username,$password)
 $request.Method = [System.Net.WebRequestMethods+FTP]::DeleteFile
 $response = $request.GetResponse()
 "Deleted from FTP: $source" -f $response.StatusDescription

$lines = GetFilesListAsArray $user1 $pass1 $local_target1 $ftp_uri1 $subfolder1
'List of files OK'
$total_files = 0
foreach ($line in $lines){
 if ($line -ne '') {
 #TRIM the file_name because if it contains blank spaces you will get errors when creating the file
 $file_name = $line.ToString().Trim()
 $source = $ftp_uri1 + $subfolder1 + $file_name
 $target = $local_target1 + $file_name
 DownloadFile $source $target $user1 $pass1
 DeleteFile $source $user1 $pass1
 $total_files = $total_files + 1
"Total files downloaded: $total_files"

If you get an error like the following when trying to execute the script:

File C:\scripts\test.ps1 cannot be loaded because the execution of scripts is disabled on this system.
Please see “get-help about_signing” for more details.

Make sure the execution of Powershell scripts is enabled:


And set it to the appropriate level:

Set-ExecutionPolicy Unrestricted


Running Windows PowerShell Scripts

Using the Set-ExecutionPolicy Cmdlet

(Powershell) Loop to delete files from an FTP Location


Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de

Estás comentando usando tu cuenta de Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s

A %d blogueros les gusta esto: