Script

FTP

The professional tool to automate FTP, SFTP, FTPS

and schedule FTP batch jobs

download_and_delete.ftp

This script downloads every txt file from the FTP server and deletes each remote file once the download is completed.

It also has error handling. Every command returned value is checked and if the command failed the script stops itself.

GETLIST and FOREACH are used here to get the remote listing and perform a set of commands for each file. This combination of commands is used when it’s necessary to handle the files separately.

# Connect to ftp.myhost.com as myuser
$result=OPENHOST("ftp.myhost.com","myuser","123456")
 
# If OPENHOST failed stop the script
IF($result!="OK")
 STOP
END IF
 
# Change the current local directory. The files
# will be downloaded here.
$result=LOCALCHDIR("C:\users\carlos\desktop\localftp")
 
# If LOCALCHDIR failed stop the script
IF($result!="OK")
 STOP
END IF
 
# Get the remote file listing, store it in $list
$result=GETLIST($list,REMOTE_FILES,"*.txt")
 
# If GETLIST failed stop the script
IF($result!="OK")
 STOP
END IF
 
# For each file in $list...
FOREACH $item IN $list
 # Download the file
 $result=GETFILE($item) 
 # If the file has been succesfully downloaded
 # delete the remote copy. If not stop the script.
 IF($result=="OK")
 DELETEFILE($item)
 ELSE
 STOP
 END IF
END FOREACH
 
# Close the connection
CLOSEHOST