Search code examples
windowsbatch-filecmd

simple batch file to delete specific files in a folder/sub folder and log the results


I'm trying to create a batch file that will delete multiple files, then append a log with those deleted files. This batch file will need to run via Windows Task Scheduler daily.

I have started off with this batch file with the ffg content (the list will be lengthy as there are lots of user files to remove)

del "[John Doe]*.wav" /s 
del "[Pete Pan]*.wav" /s 

Solution

  • To ensure logging of file deletion is active the batch file should start with,

    Setlocal ENABLEEXTENSIONS
    

    To use a list of variable names, use a for loop of list and redirect output to log.

    for /f "tokens=*" %%f in (names.txt) do del /S "[%%f]*.wav" >>Deleted.txt
    

    Thus the CMD file is at its simplest

    Setlocal ENABLEEXTENSIONS
    for /f "tokens=*" %%f in (names.txt) do del /S "[%%f]*.wav" >>Deleted.txt
    

    Where the names.txt is

    John Doe
    Joe Blogs
    Pete Pan
    

    ETC. Etc.

    Note good practice before deletion is use a test folder to ensure it is confined to one area. And ensure the file system is good perhaps by running CHKDSK once in a while!

    For those who also need to /Recurse folders. A rough outline is to wrap the loop in another, so something like:

    Setlocal ENABLEEXTENSIONS
    for /R "%~dp0" %%d in (.) do (
    cd /d "%%d"
    for /f "tokens=*" %%f in (%~dp0names.txt) do del /S "[%%f]*.wav" >>"%~dp0Deleted.txt"
    )