Noah
Noah

Reputation: 93

Delete all files in subdirectories EXCEPT a given extension (in Windows BATCH)

This has been killing me Looking for a quick, possibly for loop, blip of code (as small as possible), that will delete ALL files (not folders) in the specified directory and all subdirectories, of ANY type that's NOT .apk (in this case)

Here is what I landed on, but it does nothing. (BTW, I already have %current% set to a specific folder elsewhere in my script)

For /R %%f in (%current%\Data\TEMP\*) do (
  if not %%~xf==.apk del /S "%%f"
)

This command works in the console, exactly how I want it to. I just have to right click open a new command window in the root of the directly I want to start my cleaning in. But for whatever reason, I cant get this to work in a batch script.

For /r %f in (*) do if not %~xf==.apk del /S "%f"

Anybody have any idea why that first for loop is failing me?

Upvotes: 1

Views: 10918

Answers (1)

aschipfl
aschipfl

Reputation: 34989

for /R can lead to unexpected results when you specify more than just a file name pattern in the set (that is the part in between parentheses). So you need to put the path part immediately behind /R. (If there is nothing specified, it defaults to the current directory.) So the following should work:

for /R "%current%\Data\TEMP" %%f in (*) do (if not "%%~xf"==".apk" del "%%~f")

Upvotes: 1

Related Questions