<http://www.netikka.net/tsneti/info/tscmd060.htm>
Copyright © 2003-2012 by Prof. Timo Salmi  
Last modified Wed 21-Mar-2012 07:36:24

 
Assorted NT/2000/XP/.. CMD.EXE Script Tricks
From the html version of the tscmd.zip 1cmdfaq.txt file
To the Description and the Index
 

This page is edited from the 1cmdfaq.txt faq-file contained in my tscmd.zip command line interface (CLI) collection. That zipped file has much additional material, including a number of detached .cmd script files. It is recommended that you also get the zipped version as a companion.

Please see "The Description and the Index page" for the conditions of usage and other such information.



60} How do I delete all but most recent 20 files in a folder?

The example below comes with multiple safeguards. It prepares a new script, which you then can run. The resulting script comes with rem:s and the deletion with the /p (prompt for confirmation) switch. The possibility of file/folder names with spaces has been taken into account.

  @echo off & setlocal enableextensions
  ::
  :: Which folder to examine (customize the path!)

  set targetdir_=c:\_m\test two
  if not exist "%targetdir_%\*.*" (
    echo Folder "%targetdir_%" not found
    goto :EOF)
  ::
  :: Let the script prepare a new one (customize the path!)

  set script_="c:\_m\doit.cmd"
  if exist %script_% del %script_%
  ::
  :: Identify the files to be deleted

  for /f "skip=20 delims=" %%f in (
    'dir /a:-d /b /o:-d "%targetdir_%\*.*"') do (
      echo rem del /p "%targetdir_%\%%~nf%%~xf">>%script_%)
  ::
  :: Tell me about it

  for /f "delims=" %%s in (%script_%) do if exist %%~fs (
    echo The script "%%~fs" is ready
    echo %%~ts %%~as %%~zs)
  endlocal & goto :EOF

The contents of DOIT.CMD could become e.g.
  rem del /p "c:\_m\test two\CMDFAQ2.CMD"
  rem del /p "c:\_m\test two\test (4!).txt"
  rem del /p "c:\_m\test two\test & 3.txt"
  rem del /p "c:\_m\test two\MYTEST.CMD"
  rem del /p "c:\_m\test two\VBSFAQ.VBS"
  rem del /p "c:\_m\test two\VBSFAQ2.VBS"
  rem del /p "c:\_m\test two\BATFAQ.BAT"

References/Comments:
  Google Groups 19 Mar 2012 21:31:20