[batch-file] Delete all files of specific type (extension) recursively down a directory using a batch file

I need to delete all .jpg and .txt files (for example) in dir1 and dir2.

What I tried was:

@echo off
FOR %%p IN (C:\testFolder D:\testFolder) DO FOR %%t IN (*.jpg *.txt) DO del /s %%p\%%t

In some directories it worked; in others it didn't.

For example, this didn't do anything:

@echo off
FOR %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

What I'm I missing in the second snippet? Why didn't it work?

This question is related to batch-file cmd

The answer is


I wrote a batch script a while ago that allows you to pick a file extension to delete. The script will look in the folder it is in and all subfolders for any file with that extension and delete it.

@ECHO OFF
CLS

SET found=0
ECHO Enter the file extension you want to delete...
SET /p ext="> "

IF EXIST *.%ext% (           rem Check if there are any in the current folder :)
  DEL *.%ext%
  SET found=1
)
FOR /D /R %%G IN ("*") DO (  rem Iterate through all subfolders
  IF EXIST %%G CD %%G
  IF EXIST *.%ext% (
    DEL *.%ext%
    SET found=1
  )
)

IF %found%==1 (
  ECHO.
  ECHO Deleted all .%ext% files.
  ECHO.
) ELSE (
  ECHO.
  ECHO There were no .%ext% files.
  ECHO Nothing has been deleted.
  ECHO.
)

PAUSE
EXIT

Hope this comes in useful to anyone who wants it :)


If you are trying to delete certain .extensions in the C: drive use this cmd:

del /s c:\*.blaawbg

I had a customer that got a encryption virus and i needed to find all junk files and delete them.


You can use this to delete ALL Files Inside a Folder and Subfolders:

DEL "C:\Folder\*.*" /S /Q

Or use this to Delete Certain File Types Only:

DEL "C:\Folder\*.mp4" /S /Q 
DEL "C:\Folder\*.dat" /S /Q 

I don't have enough reputation to add comment, so I posted this as an answer. But for original issue with this command:

@echo off
FOR %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

The first For is lacking recursive syntax, it should be:

@echo off
FOR /R %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

You can just do:

FOR %%p IN (C:\Users\0300092544\Downloads\Ces_Sce_600) DO @ECHO %%p

to show the actual output.


this is it:

@echo off

:: del_ext
call :del_ext "*.txt"
call :del_ext "*.png"
call :del_ext "*.jpg"

:: funcion del_ext
@echo off
pause
goto:eof
:del_ext
 set del_ext=%1
 del /f /q "folder_path\%del_ext%"
goto:eof

pd: replace folder_path with your folder