Found several solutions for local, but need one for FTP action:
I have a daily batch script to backup MySQL databases locally, however I also ftp them to a backup server.
Locally, I am using forfiles
to delete files older than 14 days:
forfiles -p "C:\whatever" -s -m *.* -d 14 -c "cmd /c del @path"`
The same I would like to do on FTP, once the newest backup files are dumped into FTP server running on Windows Server 2008 R2.
How do I extend my batch file to do this action?
cd\[path to directory where files are saved]
echo off
echo user [ftp username]>ftpup.dat
echo [ftp password]>>ftpup.dat
echo binary>>ftpup.dat
echo put [FullBackup.%backupdate%.zip]>>ftpup.dat
echo quit>>ftpup.dat
ftp -n -s:ftpup.dat [myserver.com]
del ftpup.dat
capture the list of files you are interested in
echo user [ftp username]>ftpdir.txt
echo [ftp password]>>ftpdir.txt
echo dir . ftplist.txt >>ftpdir.txt
echo quit>>ftpdir.txt
ftp -n -s:ftpdir.txt [myserver.com]
prepare the ftp delete script
echo user [ftp username]>ftpdel.txt
echo [ftp password]>>ftpdel.txt
process the list
for /f "tokens=6,7,8,*" %%a in (ftplist.txt) do (
echo %%d
)
inside the loop, extract the file date.
echo %%c %%a %%b - %%d
And transform the month name into a number
call :month %%a
you may use the routine found in http://www.dostips.com/DtTipsStringManipulation.php
inside the loop, transform the date into a number of days since today
call :days %%c %month% %%b
this is a call to a routine that computes the days using the Fliegel-Van Flandern algorithm. See this SO question for details and implementation How can I check the time stamp creation of a file in a Windows batch script?
and finally, inside the loop, compare the resulting number, if it is bigger than, say, 14, add the file to the files to delete ftp script
IF !days! GEQ 14 echo DEL %%d >>ftpdel.txt
finish the ftp del script and execute it
echo quit>>ftpdel.txt
ftp -n -s:ftpdel.txt [myserver.com]
It's cumbersome to implement with the built-in ftp.exe
, as the very good answer by @PA. shows.
You better use some more powerful scriptable 3rd party FTP client.
For example with WinSCP FTP client, it's as trivial as:
winscp.com /ini=nul /log=delete.log /command ^
"open ftp://username:[email protected]/" ^
"rm /remote/path/*<14D" ^
"exit"
See file masks with time constraints.
(I'm the author of WinSCP)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With