This batch file could be used for the task:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SettingsFile="
for /F "delims=" %%I in ('dir "D:\TargetFolder\Settings.txt" /A-D-L /B /S 2^>nul') do if not defined SettingsFile (set "SettingsFile=1") else (del "D:\TargetFolder\Settings.txt" /A /F /Q /S >nul 2>nul & goto Continue)
:Continue
endlocal
A less compact variant of above:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SettingsFile="
for /F "delims=" %%I in ('dir "D:\TargetFolder\Settings.txt" /A-D-L /B /S 2^>nul') do (
if not defined SettingsFile (
set "SettingsFile=1"
) else (
del "D:\TargetFolder\Settings.txt" /A /F /Q /S >nul 2>nul
goto Continue
)
)
:Continue
endlocal
First, there is made sure that the environment variable SettingsFile
is not defined by chance.
Next the command DIR is executed by a separate command process started in background to search in D:\TargetFolder
for files with name Settings.txt
and output them all with full path. The output of DIR is captured by FOR and processed line by line if DIR found the file Settings.txt
at all.
The environment variable SettingsFile
is defined with a string value which does not really matter on first file Settings.txt
. The FOR loop finishes without having done anything else if there is no more file Settings.txt
.
But on second file Settings.txt
is executed the command DEL to delete in the specified folder and all its subfolders the file Settings.txt
. The loop is excited with command GOTO to continue batch file processing on the line below label Continue
as the other occurrences of Settings.txt
do not matter anymore and of course do not exist anymore on deletion of all Settings.txt
was successful.
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
del /?
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
set /?
setlocal /?
Read the Microsoft documentation about Using command redirection operators for an explanation of >nul
and 2>nul
. The redirection operator >
must be escaped with caret character ^
on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir
command line with using a separate command process started in background with cmd.exe /c
and the command line within '
appended as additional arguments.
See also single line with multiple commands using Windows batch file for an explanation of operator &
.