Search code examples
batch-filedirectorysubdirectoryworking-directory

How can I count subfolders in a Batch file


I need the count of the longest path in my folder and put it in a variable. Because when I remove recursively subfolders I have to do it multiple times to check if there is other empty folders.

FOR /l %%y IN (0, 1, 3) DO (
FOR /r "%MyPath%" /d %%F IN (.) DO DIR /b "%%F" | findstr "^" > NUL || RD "%%F"
)

I don't know if there is a parameter that I can use to remove all of my empty subfolders but all I found is this way and I need to replace the 3 with the count of subfolders in my biggest path.


Solution

  • for /f "delims=" %%s in ('dir /s /b /ad "%sourcedir%"^|sort /r') do dir /b "%%s"|findstr "^" > NUL|| RD "%%s"
    

    should delete your empty directories.

    The dir command lists the directories in the tree rooted at sourcedir. This is sorted in reverse order so the subdirectories of any subdirectory are processed before the subdirectory.

    I'd target a test directory for - well, testing...