1

I am trying to write a simple batch file that deletes all files in a directory and its containing sub folders that DON'T match some file extensions.

Logic is like this:

GOTO directory
delete !(.avi, .mkv, .mp4)

Thought this would be simple enough but I have tried multiple times with no luck!

Nayan
  • 3,014
  • 2
  • 17
  • 33
dannmate
  • 106
  • 3
  • 12
  • If you want to avoid loop, if etc., move required files to another directory. Delete remaining files, & then move back 'required' files. It looks more scalable than for loop+nested if's. – anishsane Nov 07 '12 at 12:36
  • possible duplicate of [Delete \*.\* excluding some extensions](http://stackoverflow.com/questions/9424380/delete-excluding-some-extensions) – finnw Nov 07 '12 at 16:21

3 Answers3

1
@echo off
for /r C:\test %%a in (*) do (
if not %%~xa==.avi (
    if not %%~xa==.mkv (
        if not %%~xa==.mp4 (    
            del /f /q "%%a"
        )
    )
)
)

Just repeat the if's for the extensions that you don't want to delete.

This answer will work for a few extensions, but if you have any more you would find a better answer here.

Community
  • 1
  • 1
Bali C
  • 30,582
  • 35
  • 123
  • 152
1

This question is nearly identical to Delete *.* excluding some extensions, except you want to delete from the sub-directories as well. Either of the following adaptations of the top two answers should work.

Both of the following assume your batch script is not in the folder hierarchy that is getting deleted.

@echo off
for /f %%F in ('dir /s /b /a-d "yourDirPath\*"^| findstr /vile ".avi, .mkv, .mp4"') do del "%%F"

.

@echo off
setlocal EnableDelayedExpansion
set "exclude=.avi.mkv.mp4."
for /r "yourDirPath" %%F in (*) do if /I "%exclude%" == "!exclude:%%~xF.=!" del "%%F"


If your script is in the hierarchy, then an extra IF statement will fix the problem.

@echo off
for /f %%F in ('dir /s /b /a-d "yourDirPath\*"^| findstr /vile ".avi, .mkv, .mp4"') do if "%%~fF" neq "%~f0" del "%%F"

.

@echo off
setlocal EnableDelayedExpansion
set "exclude=.avi.mkv.mp4."
for /r "yourDirPath" %%F in (*) do if /I "%exclude%" == "!exclude:%%~xF.=!" if "%%~fF" neq "%~f0" del "%%F"
Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390
0

Similar to this question: How can I delete files that don't match a wildcard?

FOR /R [directory] %%F IN (*.*) DO IF NOT "%%~xF" == ".[extension]" DEL /F /S "%%F"
Community
  • 1
  • 1
Ahmad
  • 12,336
  • 6
  • 48
  • 88