Search code examples
batch-filecmdcommand

If a file was found more than once in subfolders - delete all using batch script


The system I'm working on looks like this:

D:\TargetFolder\Subfolder1 
D:\TargetFolder\Subfolder2\Subfolder3

There is a file called "Settings.txt" that could exist in each of these folders. what I want is the following:

  • If the file was found more than once in the targeted folder and all of its subfolders then delete all of them.

  • If the file was found just once in the targeted folder and all of its subfolders then continue on with the script.

  • If the file doesn't exist then continue on with the script.

The final script could possibly be something like this:

IF exist "D:\TargetFolder\*Settings.txt" (goto delete) else goto continue
:delete
del *Settings.txt /f /q
:continue
exit

I hope I explained my question correctly. Thanks in advance.


Solution

  • @echo off
    
    for /F "skip=1" %%a in ('dir /B /S D:\TargetFolder\Settings.txt 2^>NUL') do (
       del /Q /S D:\TargetFolder\Settings.txt >NUL
       goto break
    )
    :break
    

    The for /F loop process file names from dir /S command, but the first one is skipped (because "skip=1"switch), that is to say, if there are more than one file, the next commands are executed.

    The first command in the for deletes all files with "Settings.txt" name and the for is break because the goto command.