Copyright © 2003-2012 by Prof. Timo Salmi  
Last modified Wed 21-Mar-2012 07:38:36

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.

100} How can I identify and copy the five latest files from a folder?

  @echo off & setlocal enableextensions enabledelayedexpansion
  set count_=0
  for /f "delims=" %%f in (
    'dir /o:-d /a:-d /b c:\_d\test\*.*') do (
    set file_="%%~ff"
    set /a count_+=1
    if !count_! LEQ 5 echo rem copy !file_!
  endlocal & goto :EOF

The output could be e.g.
  rem copy "C:\_D\BAS\CMDFAQ.CMD"
  rem copy "C:\_D\BAS\My File 1.txt"
  rem copy "C:\_D\BAS\My test file.txt"
  rem copy "C:\_D\BAS\VBSFAQ.VBS"
  rem copy "C:\_D\BAS\CMDFAQ2.CMD"

Given that solution it is as easy to identify the five oldest files. Left as an exercise.

The problem with the solution above is that it can't handle file names with exclamation marks! To counter that, use
  @echo off & setlocal enableextensions disabledelayedexpansion
  set count_=0
  for /f "delims=" %%f in (
    'dir /o:-d /a:-d /b c:\_d\bas\*.*') do (
    call :SubCount "%%~ff")
  endlocal & goto :EOF
  set /a count_+=1
  if %count_% LEQ 5 echo rem copy %1
  goto :EOF

  Google Groups 19 Mar 2012 21:31:20