Skip to content

Instantly share code, notes, and snippets.

@Waxolunist
Created February 22, 2012 15:23
Show Gist options
  • Save Waxolunist/1885529 to your computer and use it in GitHub Desktop.
Save Waxolunist/1885529 to your computer and use it in GitHub Desktop.
Delete all files in a directory except the n newest on Windows
:: ****************************************************************************
:: Delete all files except the n newest
:: ****************************************************************************
:: ----------------------------------------------------------------------------
:: Usage: delete_except_newest.bat DIR N FILTER
:: Example: delete_except_newest.bat C:\tmp 10 *.txt
:: ----------------------------------------------------------------------------
:: ****************************************************************************
:: ****************************************************************************
:: Init
REM CLS
@ECHO off
SetLocal EnableDelayedExpansion
:: ****************************************************************************
@ECHO.
:: ****************************************************************************
:: Variables
:: ****************************************************************************
SET DIR=%1%
SET /a N=%2%
SET FILTER=%3%
:: ****************************************************************************
REM list all filenames, except directories, sorted by date of creation, newest first
for /F "skip=%N% tokens=*" %%G in ('dir /T:C /O:-D /B /A:-D "%DIR%\%FILTER%"') DO DEL "%DIR%\%%G
@ECHO Program exited successfully.
:: ****************************************************************************
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment