Reputation: 111
I'm trying to make a batch file on Windows for deleting all the files in the current directory but excluding 4 file extensions (log, sdb, SDK, bat).
I have tried the Forfiles command on Windows but this delete everything on my current folder (even the bat file). My command is:
@ECHO OFF
FORFILES /M *.* /C "cmd /c IF NOT @ext=="sdb" (IF NOT @ext=="sbk" (IF NOT @ext=="log" (IF NOT @ext=="bat" DEL @FILE)))" /Q
How can I make it work?
Upvotes: 11
Views: 40300
Reputation: 130839
\
IF /I
(case insensitive) optionThis should work
@echo off
forfiles /c "cmd /c if @isdir equ FALSE if /i not @ext==\"sdb\" if /i not @ext==\"sbk\" if /i not @ext==\"log\" if /i not @ext==\"bat\" del @file"
But the above is very slow, and it sure is a lot to type.
The following is much simpler and faster.
@echo off
for /f "delims=" %%F in ('dir /b /a-d ^| findstr /vile ".sdb .sbk .log .bat"') do del "%%F"
Upvotes: 13
Reputation: 1
I ran across this topic searching for a way to delete hundres of files created by a virus. Non of the solutions really worked for me, so I figured out how to do it from a command line. I needed only to keep 2 extensions (mail archive). This did the trick:
for /R %f in (*) do if not %~xf==.ex1 if not %~xf==*.ex2 del "%f"
I use the /R to work recursive: look in all subfolders. The %~xf looks at the extension only (for some reason it didn't work without it). I use the quotes "%f" at the delete command to cover the windows long names with spaces (especially in folder names). Also for some reason, adding spaces before and behing the == gave errors.
Upvotes: -1
Reputation: 21
forfiles /s /c "cmd /c (if NOT @ext==\"dqy\" del /s /q @path)" /D -14
This is about as simple as I could get this script. They wanted to keep the macro files (.dqy) but recursively delete everything else older than 14 days.
Upvotes: 2
Reputation: 51
Also, you can do something like this:
@echo off
attrib -r -s *.*
attrib +r +s *.sdb
attrib +r +s *.sbk
attrib +r +s *.log
attrib +r +s *.bat
del *.* /S /Q
attrib -r -s *.sdb
attrib -r -s *.sbk
attrib -r -s *.log
attrib -r -s *.bat
-- Mario
Upvotes: 5
Reputation: 77677
If ROBOCOPY
is available to you:
@ECHO OFF
MKDIR temporary_pit
ROBOCOPY . temporary_pit /XF *.sdb *.sbk *.log *.bat /MOV >NUL
RMDIR /S /Q temporary_pit
That is, you are creating a temporary subdirectory, moving the files that are to be deleted to it (which is fast because, as the destination directory is on the same drive, only file names are relocated, not the files' contents), then deleting the subdirectory.
Upvotes: 10
Reputation: 67216
@echo off
setlocal EnableDelayedExpansion
set exclude=.log.sdb.sdk.bat.
for %%f in (*.*) do (
if /I "%exclude%" == "!exclude:%%~Xf.=!" del "%%f"
)
Upvotes: 3