I am writing a script using ftp.exe
to download files from an FTP server, it works at first. But the version I wrote was suited for only one file and the current date. My script is below:
echo user>>ftp.txt
echo password>>ftp.txt
set prefix=%date:~0,10%
set "name=%prefix%.txt"
echo get %name% >> ftp.txt
echo bye >> ftp.txt
ftp -s:ftp.txt ftpserver.com
del ftp.txt
But now there are more than one file named like aa-bb-2011-09-13.0.log
,
aa-bb-2011-09-13.1.log
,
aa-bb-2011-09-13.10.log
. The last number is a serial number, it could be 0
, 1
, 2
, 3
...
How could download these files by batch script? How to modify my script to download more than one file (the number is unknown) which file name pattern is yesterday?
This is a sample FTP script that does almost exactly what you need but it uses a 3rd party client instead of the one that comes free with Windows: http://kb.robo-ftp.com/script_library/show/45
Maybe you can convert it.
In terms of downloading multiple files, use
mget
instead ofget
. The former allows you to specify wildcards for getting rather than specific files.You'll just have to construct the "name" with a wildcard pattern, and make sure you have a
prompt
in your script beforemget
otherwise it will ask for confirmation on every file.This is untested, but it's probably as simple as changing:
to something like:
In terms of getting yesterdays date, you can use the following script. It's pretty complex compared to what you would do in, for example
bash
, but it works.It will set the
yesterday
environment variable to the formatYYYY-MM-DD
so that you can use it in your current script. Simply invokecall yesterday.cmd
and then use the environment variable.It's a pretty complex task to implement with Windows batch-file and the built-in FTP client (
ftp.exe
).It would be more easier with PowerShell.
And even easier using a more capable FTP client, like the latest version of WinSCP FTP client.
If you want to download files based on a pattern in a file name, this will do:
This uses the
%TIMESTAMP%
syntaxIf you want to download based on a file modification time, use a file mask with a time-constraint:
The
>=yesterday<today
syntax is supported by WinSCP 5.15 and newer.In older versions of WinSCP, you can again use
%TIMESTAMP%
syntax, particularly>=%%TIMESTAMP-1D#yyyy-mm-dd%%<%%TIMESTAMP#yyyy-mm-dd%%
, instead of>=yesterday<today
.(I'm the author of WinSCP)