Batch file to download the latest file from FTP server
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 thewmic os get LocalDateTime
. -
If you can determine the latest file alphabetically, you can:
- run the
ftp.exe
withls
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.
- run the
-
WinSCP can download the latest file, using the
-latest
switch of theget
command:winscp.com /command ^ "open ftp://username:[email protected]/" ^ "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:[email protected]/" ^ "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:[email protected]/" ^ "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 thewmic os get LocalDateTime
(as shown above). Use the%TIMESTAMP%
syntax:winscp.com /command ^ "open ftp://username:[email protected]/" ^ "cd /remote/path" ^ "get %%TIMESTAMP#yyyy-mm-dd%%.txt" ^ "exit"
(I'm the author of WinSCP)
Stan
Updated on July 21, 2022Comments
-
Stan almost 2 years
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.