LabRat
LabRat

Reputation: 2014

Check file name before deletion (windows Batch)

Is there a way using Windows Batch to read a txt file list of file names. And if the name is present in the list to preserve that file but. If the file name is not found in the txt list that it is deleted.

I namely trying to filter out a horde of temporary files automatically generated by not cleaned out by AutoCAD.

The reason for reading a txt list would allow me to add or delete file names for processing.

Upvotes: 1

Views: 314

Answers (1)

Andreas
Andreas

Reputation: 5599

Yes this is possible with Windows batch. Assuming you got a list of files FilesToKeep.txt with filenames like this:

WillBeKept.txt
WillAlsoBeKept.doc

in the same directory as the following batch script:

@echo OFF
pushd "%~dp0"
set "PathToCleanup=E:\Temp\Test"
for /F "tokens=*" %%F in ('dir /S/B/A-D %PathToCleanup%\*.*') do (
     findstr /S %%~nxF FilesToKeep.txt >NUL || del /Q "%%F" )

This script loops through all files in PathToCleanup and if a filename is not present in FilesToCleanup.txt then the file will be deleted.

Upvotes: 2

Related Questions