Batch file to download the latest file from FTP server
batch-file, ftp
Solution
There's no easy way to select the most recent file with the `ftp.exe`.
If you know that the file has today's timestamp in its filename, you can generate the script dynamically with today's timestamp. You can use the `DATE` environment variable, though it has its caveats. A more reliable (and complex) way is to use the `wmic os get LocalDateTime`.
See How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?
If you can determine the latest file alphabetically, you can:
- run the `ftp.exe` with `ls` command redirected to a file
- sort the file by alphabet in descending order
- read the first line
- generate download script for second `ftp.exe` run.
WinSCP can download the latest file, using the `-latest` switch of the `get` command:
winscp.com /command ^
"open ftp://username:password@ftp.example.com/" ^
"cd /remote/path" ^
"get -latest *.csv" ^
"exit"
See also the guide to downloading the most recent file with WinSCP.
WinSCP can also download the files created within some interval, e.g. the last 24-hours (1 day):
winscp.com /command ^
"open ftp://username:password@ftp.example.com/" ^
"cd /remote/path" ^
"get *.csv>=1D" ^
"exit"
or files created since some point in time, e.g. to download files created since midnight, use `today` keyword:
winscp.com /command ^
"open ftp://username:password@ftp.example.com/" ^
"cd /remote/path" ^
"get *.csv>=today" ^
"exit"
For the `today` keyword, make sure you have recent version of WinSCP.
With WinSCP, you can implement a download of a file with a timestamp in filename more easily than with the `DATE` or the `wmic os get LocalDateTime` (as shown above). Use the `%TIMESTAMP%` syntax:
winscp.com /command ^
"open ftp://username:password@ftp.example.com/" ^
"cd /remote/path" ^
"get %%TIMESTAMP#yyyy-mm-dd%%.txt" ^
"exit"
(I'm the author of WinSCP)
Problem
I have a batch file that FTPs CSV files from my web server. I need to download only the most current CSV file. How do I do that? This is what I have so far: ``` open 44.44.44.444 username password CD /Client/ABCCompany/ get *.csv quit close() ``` Thanks.