Wednesday 11 November 2015

Using PowerShell-FTP-Client to download and delete files from an FTP server

  1. Configure PowerShell - out the scope of this blog entry, but here with Microsoft
  2. Download and install the PowerShell FTP Client Module by Michal Gajda.
  3. Use the code below which logs on to the FTP server and then gets a list of files
  4. Downloads each file in the list
  5. Deletes the file after download
$FtpServer = "ftp.server.com"
$User = "username"
$PWD = "cleverpassword"
$Password =  ConvertTo-SecureString $Pwd -AsPlainText -Force
$FtpCredentials = New-Object System.Management.Automation.PSCredential ($User, $Password)
Set-FTPConnection -Credentials $FtpCredentials -Server $FtpServer -Session MyFtpSession -UsePassive 
$FtpSession = Get-FTPConnection -Session MyFtpSession
$ServerPath = "/backups/test/"
$LocalPath  = "C:\Data\test\"
$fileList   = Get-FTPChildItem -Session $FtpSession -Path $ServerPath -Filter *.txt
foreach ($element in $fileList ) {
 $filename = $ServerPath  + $element.name
 Get-FTPItem    -Path $filename -Session $FtpSession -LocalPath $LocalPath -Overwrite $true
    Remove-FTPItem -Path $filename -Session $FtpSession 
}

No comments:

Post a Comment