Batch delete files on FTP older than x days

Found multiple solutions for local, but need one for the FTP action:

I have a daily batch script to back up MySQL databases locally, however I am also uploading them to a backup server.

Locally I use forfiles

to delete files older than 14 days:

forfiles -p "C:\whatever" -s -m *.* -d 14 -c "cmd /c del @path"`

      

The same thing I would like to do on FTP, once the most recent backup files are dumped to an FTP server running on Windows Server 2008 R2.

How do I renew the batch file to do this?

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

      

+3


source to share


2 answers


  • grab 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 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 date of the file.

    echo %%c %%a %%b - %%d
    
          

    And convert the name of the month to a number

    call :month %%a
    
          

    you can use the procedure found at http://www.dostips.com/DtTipsStringManipulation.php

  • inside a loop, convert the date to the number of days from today

    call :days %%c %month% %%b
    
          

    it is a call to a procedure that calculates days using the Fliegel-Van Flandern algorithm. See this SO question for details and implementation How can I test creating a file timestamp in a Windows batch script?

  • and finally, inside the loop, compare the resulting number, if it is greater than, say 14, add the file to the files to remove the ftp script

    IF !days! GEQ 14 echo DEL %%d >>ftpdel.txt
    
          

  • end ftp del script and execute it

    echo quit>>ftpdel.txt
    ftp -n -s:ftpdel.txt [myserver.com]
    
          



+4


source


This is very difficult to implement with inline ftp.exe

, as @PA's very good answer shows. ...

You are better off using a more powerful scripted third party FTP client.


For example, for a WinSCP FTP client, it's as simple as:



winscp.com /ini=nul /log=delete.log /command ^
    "open ftp://username:password@ftp.example.com/" ^
    "rm /remote/path/*<14D" ^
    "exit"

      

See file masks with time limits .

(I am the author of WinSCP)

+4


source







All Articles