< lang-dos -->
@ECHO OFF
SETLOCAL
SET "targetdir=c:\sourcedir"
SET "pfname="
PUSHD "%targetdir%"
FOR /f "delims=" %%a IN ('dir /b /a-d /o:d "*" ') DO (
SET "fname=%%a"
SET "fdate=%%~ta"
CALL :process
)
POPD
GOTO :EOF
:process
:: reformat date - this depends on yout local date-format.
:: YY(YY)MM required - my format is dd/mm/yyyy
SET fdate=%fdate:~6,4%%fdate:~3,2%
IF NOT DEFINED pfname GOTO nodel
IF %fdate%==%pfdate% ECHO DEL "%targetdir%\%pfname%"
:nodel
SET pfdate=%fdate%
SET "pfname=%fname%"
GOTO :eof
This should work for you. The required DEL commands are merely ECHO
ed for testing purposes. After you've verified that the commands are correct, change ECHO DEL
to DEL
to actually delete the files.
First, the target directory is set up and pfname
is cleared.
The PUSHD
changes the current directory
until the POPD
is executed
the dir
command outputs filenames only (/b
), no directory names (/a-d
) in date-order (/o:d
). Each line sets fname
to the filename and fdate
to the filedate.
within :process
, the date-string is manipulated. I don't know which format you use, but the basic formula is %variable:~startposition,length%
where startposition starts at 0=first character. The idea is to have fdate
in the format yyyymm
if pfname
(previos filename) is not set, this is the first file found, so we don't delete that.
For every other file, if the filedate is the same as the previous filedate, then delete the previous filename.
The current filename/date is then recorded as the previous version.
Done!