8

How do you find all empty directories using batch script?

I have a folder called "shows" on my desktop. Inside it has many sub directories. Some directories are empty and other have some files in them.

How can I loop though all the sub folder and print all folders which are empty?

Below is what I have tried. Issue is that it prints out all folders... even if a sub folder is not empty.

@echo off

SET "MYPATH=C:\Users\dave\Desktop\shows"

 for /d %%a in ("%mypath%\*") do (
    dir /b /s "%MYPATH%"
    pause
)
pause

2 Answers 2

12

Here is one way.

From the command line:

for /r "C:\Users\dave\Desktop\shows" /d %F in (.) do @dir /b "%F" | findstr "^" >nul || echo %~fF

Using a batch script:

@echo off
setlocal
set "myPath=C:\Users\dave\Desktop\shows"
for /r "%myPath%" /d %%F in (.) do dir /b "%%F" | findstr "^" >nul || echo %%~fF
1
  • 1
    Why is this not marked as answer? This script works like a charm.
    – Shuaib
    Commented Aug 24, 2023 at 15:23
5

You can use PowerShell! This one-liner will do the trick:

Get-ChildItem 'C:\Users\dave\Desktop\shows' -Recurse -Directory | Where-Object {[System.IO.Directory]::GetFileSystemEntries($_.FullName).Count -eq 0} | ForEach-Object {$_.FullName}

The first part (starting with Get-ChildItem) finds all the subdirectories of that one folder. The second part (Where-Object) filters those results down to those that have no file system entries of any kind, neither files nor folders. Finally, the ForEach-Object part spits out the found folder's full name.

We can condense that line quite a bit by using aliases and abbreviations:

gci -Dir -r | ? {[IO.Directory]::GetFileSystemEntries($_.FullName).Count -eq 0} | % {$_.FullName}

Finally, you can call it from batch:

powershell -command "gci -Dir -r | ? {[IO.Directory]::GetFileSystemEntries($_.FullName).Count -eq 0} | % {$_.FullName}"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .