The following batch file could be used for this task:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "TargetFolder=%~1"
if not defined TargetFolder set "TargetFolder=."
set "ExcludeBatchFile="
for %%I in ("%TargetFolder%\") do if "%%~dpI" == "%~dp0" set "ExcludeBatchFile=/C:"%~nx0""
for /F "eol=| delims=" %%I in ('dir "%TargetFolder%\" /AD /B 2^>nul ^| %SystemRoot%\System32\findstr.exe /I /L /V /X /C:"special folder"') do rd /S /Q "%TargetFolder%\%%I"
for /F "eol=| delims=" %%I in ('dir "%TargetFolder%\" /A-D /B 2^>nul ^| %SystemRoot%\System32\findstr.exe /I /L /V /X /C:"1.bat" %ExcludeBatchFile%') do del /A /F "%TargetFolder%\%%I"
endlocal
for /F
with dir
is used instead of for /D
to process also subdirectories with hidden attribute set. for /D
ignores subdirectories with hidden attribute.
This batch file runs the directory cleanup on the directory passed as argument to the batch file. It makes the cleanup on current directory if batch file is started without any argument.
The batch file protects itself on being deleted on deleting files in current directory or in a specified target directory and batch file is in current directory or the specified target directory. But the batch file does not protect itself on being deleted if the batch file is stored in any subdirectory of the current directory or specified target directory.
There can be multiple /C:"Directory Name"
arguments specified on second FOR command line to exclude multiple subfolders in target folder for being removed by the batch file.
There can be multiple /C:"File Name"
arguments specified on third FOR command line to exclude multiple files in target folder for being removed by the batch file.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
del /?
dir /?
echo /?
endlocal /?
findstr /?
for /?
if /?
rd /?
setlocal /?
Read the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul
and |
. The redirection operators >
and |
must be escaped with caret character ^
on both FOR command lines to be interpreted as literal characters when Windows command interpreter processes these command lines before executing command FOR which executes the embedded command line with dir
and findstr
with using a separate command process started in background using %ComSpec% /c
and the specified command line.