Windows Batch Scripting - Keep only 2 newest files in directory

Discussion in 'Software' started by hem852, Aug 24, 2009.

  1. hem852

    hem852 Private E-2

    Hi,

    What I need to do is make a batch script delete all files in a specific directory apart from the newest 2 files.

    I've seen lots of stuff about deleting files older than 'x' days but these don't really fit with what I need and I haven't been able to modify one to successfully do what I need.

    Anyone got any idea how I can accomplish this?

    Regards
    John
     
  2. GermanOne

    GermanOne Guest

    Hi,
    you could try this to show the files you want to delete:
    Code:
    @echo off &setlocal
    set folder=C:\test
    
    pushd "%folder%"
    for /f "skip=2 tokens=*" %%i in ('dir /a:-d-s /b /o:-d') do echo "%%i"
    popd
    
    pause
    
    If you think its OK then replace "echo" with "del" to delete them.
     

MajorGeeks.Com Menu

Downloads All In One Tweaks \ Android \ Anti-Malware \ Anti-Virus \ Appearance \ Backup \ Browsers \ CD\DVD\Blu-Ray \ Covert Ops \ Drive Utilities \ Drivers \ Graphics \ Internet Tools \ Multimedia \ Networking \ Office Tools \ PC Games \ System Tools \ Mac/Apple/Ipad Downloads

Other News: Top Downloads \ News (Tech) \ Off Base (Other Websites News) \ Way Off Base (Offbeat Stories and Pics)

Social: Facebook \ YouTube \ Twitter \ Tumblr \ Pintrest \ RSS Feeds