0

I am new to writing windows batch code. I am trying to remove files from a folder that are older than 3 days old but are checked before deleting to make sure it deletes all matching files. For instance...

123456.html
123456.txt
123456.xxx
987654.html
987654.txt

Given the list of files, I would want the batch to locate the .xxx files and delete it and any matching files with that file prefix when all three are older than 3 days old.

I found the following on the internet:

@ECHO Off
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=C:\Users\ad9f2p\TEST CLEANUP"
FOR /f "delims=" %%a IN (
 'dir /b /a-d "%sourcedir%\*" '
) DO (
 SET "filename=%%a"
 SET "filename=!filename:*.XXX=!"
 IF "!filename!"=="!filename:_=!" ECHO DEL "%sourcedir%\%%a"
)
Pause
GOTO :EOF

I changed the file name suffix here to .xxx in hopes of deleting all matching, but it echoed everything in the directory to delete. It should have left the 987654 files alone.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
  • 2
    You will need to use `FORFILES` if you wan to select files based on file age. – Squashman Oct 05 '17 at 20:01
  • You should also read the help file for the `FOR` command. Especially the last section where it explains what this does: `%~nI` – Squashman Oct 05 '17 at 20:03
  • Your requirement is not clear. My interpretation is that if all files with a given base name, regardless of extension, are > 3 days old, then all files with that base name should be deleted. But if at least one file with base name is <= 3 days old, then preserve all files with that base name. But I am not sure if that is your intent. – dbenham Oct 05 '17 at 20:09
  • 1
    NB: batch is interesting from a retro-computing perspective and there are certain specialized tasks for which it is particularly well-suited (but not this one!) but if you aren't already an expert and just want to get the job done it may not be the best choice. Depending on your background, you might want to consider vbscript or Powershell. – Harry Johnston Oct 05 '17 at 20:20

0 Answers0