Dear MilanSalka
To create a BAT file that recursively searches for and deletes all files with a specific extension (e.g., .bak) in a directory and its subdirectories, follow the steps below:
Step 1: Create the delete_files.bat file
- Open Notepad or any text editor.
- Copy the following code into the editor:
==========================================================================
@echo off
:: Ensure the file extension is provided as an argument
if "%1"=="" (
echo Please provide the file extension to delete (e.g., .bak)
echo Usage: delete_files.bat .extension
pause
exit /b
)
:: Search and delete files
echo Searching and deleting all files with the extension %1 ...
for /r %%i in (*%1) do (
echo Deleting: %%i
del /f /q "%%i"
)
echo Done!
pause
===========================================================================
- %1: Refers to the file extension passed as an argument (e.g., .bak).
- for /r: Recursively searches through the current directory and all subdirectories.
- del /f /q: Deletes files forcefully without prompting ("/f" is for force, "/q" is quiet mode).
- Save the file:
- Click on File > Save As.
- Choose a location (e.g., Desktop), and name it delete_files.bat.
- Ensure the file type is set to All Files (*.*) and save it with the .bat extension.
===========================================================================
Step 2: Run the BAT File
- Navigate to the directory where you saved the delete_files.bat file.
- Open a command prompt in this directory:
- Right-click inside the folder, then select Open in Terminal (or equivalent option like Open Command Window Here).
- Run the batch file with the extension you want to delete:
delete_files.bat .bak
- Replace .bak with the desired file extension (e.g., .tmp).
- The batch file will:
- Search for all files with the specified extension in the current directory and subdirectories.
- Delete them.
Display a list of deleted files.
Best Wish
Shawn.Z-MSFT | Microsoft Community Support Specialist