LPChip
LPChip

Reputation: 884

Remove all empty folders in a subfolder using a batchfile?

I have a script that will delete all files older than 31 days from a nested file structure.

At some point, it will leave empty folders in place, and I'm looking for a way to delete them, ideally keep folders that are newer than 31 days. Given that rd FolderName will not remove a folder if its not empty, I can use this to delete folders. The problem is, if I do this, it will not remove all empty folders, only the one that is deepest in the tree. If I could reverse the list forfiles gives me, it would work. If that's not possible, is there another way?

NB: rd /s will not just remove folders nested, but will also remove its files. I don't want to remove the folder if its not empty.

Here's my script:

@echo off
cd /d "C:\MyPath"

:: remove files that are older than 31 days (retention period)
forfiles /s /d -31 /c "cmd /c if @isdir==FALSE del @relpath")

:: attempt to remove folders (will fail if the folder is not empty.)
forfiles /s /d -31 /c "cmd /c if @isdir==TRUE rd @relpath"

The above script will only remove the deepest folder. I suppose I could execute forfiles 8 times in a row, but that's a serious waste of resources.

Upvotes: 0

Views: 8490

Answers (2)

LPChip
LPChip

Reputation: 884

With help from @Magoo, who pointed out I can use sort /r to reverse a list, I managed to get to a solution.

The code used is as follows:

@echo off
cd /d "C:\MyPath"

:: remove files that are older than 31 days (retention period)
forfiles /s /d -31 /c "cmd /c if @isdir==FALSE del @relpath")

:: attempt to remove folders (will fail if the folder is not empty.)
for /f %%i IN ('forfiles /s /d -31 /c "cmd /c if @isdir==TRUE echo @relpath" ^|sort /r') DO rd %%i

Upvotes: 0

Compo
Compo

Reputation: 38719

For the removal of the no content directories the following, as already implied by @Magoo would be better and much faster than your own answer:

FOR /F "DELIMS=|" %%A IN ('DIR/B/S/AD-S-L^|SORT/R') DO RD "%%A" 2>NUL

Upvotes: 2

Related Questions