@echo off setlocal enabledelayedexpansion :: Parse command line arguments set "TARGET_DIR=%~1" set "KEEP_FILES=%~2" :: Use current directory if TARGET_DIR not provided if "%TARGET_DIR%"=="" set "TARGET_DIR=%CD%" :: Default keep files if not provided if "%KEEP_FILES%"=="" set "KEEP_FILES=*.log *.cfg" :: Display usage if help requested if "%~1"=="-h" goto :usage if "%~1"=="--help" goto :usage if "%~1"=="/?" goto :usage :: Confirm the operation echo WARNING: This will delete all files in "%TARGET_DIR%" and subdirectories echo EXCEPT files matching these patterns: %KEEP_FILES% echo. set /p confirm="Are you sure? (Y/N): " if /i not "%confirm%"=="Y" ( echo Operation cancelled. exit /b ) :: Change to target directory cd /d "%TARGET_DIR%" 2>nul if errorlevel 1 ( echo ERROR: Cannot access directory "%TARGET_DIR%" pause exit /b 1 ) echo. echo Processing files in: %TARGET_DIR% echo Keep patterns: %KEEP_FILES% echo. :: Process all files recursively for /r %%f in (*) do call :ProcessFile "%%f" echo. echo Operation completed! pause exit /b :: Subroutine to process individual file :ProcessFile setlocal enabledelayedexpansion set "filepath=%~1" set "filename=%~nx1" set "skip=0" :: Check if current file matches any keep pattern for %%k in (%KEEP_FILES%) do ( if /i "%filename%"=="%%k" ( set "skip=1" goto :skipcheck ) ) :: Check wildcard patterns if %skip%==0 ( for %%k in (%KEEP_FILES%) do ( set "pattern=%%k" set "matched=0" :: Check if pattern contains wildcards echo !pattern! | findstr /C:"*" >nul 2>&1 if !errorlevel!==0 set "has_wildcard=1" if not defined has_wildcard ( echo !pattern! | findstr /C:"?" >nul 2>&1 if !errorlevel!==0 set "has_wildcard=1" ) if defined has_wildcard ( :: Simple wildcard matching - if pattern is *.jpg, check if filename ends with .jpg if "!pattern:~0,1!"=="*" ( set "extension=!pattern:~1!" if /i "!filename:~-4!"=="!extension!" ( set "skip=1" goto :skipcheck ) ) ) ) ) :skipcheck :: Delete if not in keep list if %skip%==0 ( echo Deleting: %filepath% del "%filepath%" 2>nul if errorlevel 1 echo WARNING: Could not delete %filepath% ) else ( echo Keeping: %filepath% ) endlocal exit /b exit /b :usage echo. echo Selective File Deletion Script echo Usage: %~nx0 [TARGET_DIR] [KEEP_FILES] echo. echo Arguments: echo TARGET_DIR - Directory to process (default: current directory) echo KEEP_FILES - Space-separated patterns of files to keep (supports wildcards) echo. echo Examples: echo %~nx0 - Delete all files in current dir except *.log *.cfg echo %~nx0 "C:\MyFolder" - Delete all files in C:\MyFolder except *.log *.cfg echo %~nx0 "C:\MyFolder" "*.txt *.ini" - Keep only .txt and .ini files echo %~nx0 "." "important.* *.log config.?" - Keep files matching these patterns echo. echo Wildcard patterns supported: echo * - Matches any number of characters echo ? - Matches single character echo. exit /b