Batch file that keeps the 7 latest files in a folder
15:28 13 Nov 2012

Can anyone help me create a batch file? Basically, my goal is to create a batch file that will keep the LATEST 7 .txt files (in other words, the newest) in the folder and subsequently delete the rest. That's IF there are more than 7 files in the folder.

The problem I'm having right now is the fact that the batch file that I have created deletes most of the files because their date is from a month or two or so. I want to keep the latest 7 files at all times no matter how old they are.

So this is what I have -

@echo off

setlocal enableextensions

rem ********************************************************************************
rem *******************************  LOCAL VARIABLES  ******************************
rem ********************************************************************************

SET TargetDirectory="C:\TEMP\test"

SET No_of_fles_to_keep=7

SET count=0 

set cnt=0

rem ********************************************************************************

cd /d %TargetDirectory%

REM timeout /T 500

 for %%x in (*) do set /a count+=1

 for %%A in (*.bat) do set /a cnt+=1

cd /d %TargetDirectory%

REM timeout /T 500

IF %count% gtr %No_of_fles_to_keep% forfiles -p %TargetDirectory% -s -m "*.txt" -d -%No_of_fles_to_keep% -c "cmd /c del @path"

echo %count% 

echo File count = %cnt% 

Any help is appreciated.

file batch-file delete-file