How to find all empty directories in Windows? For Unix there exists find. So there is an out of the box solution. What is the best solution using Windows?
3 Answers
I found several solutions so far:
- Use Powershell to find empty directories
- Install Cygwin or Gnu Findtools and follow the unix approach.
- Use Python or some other script language, e.g. Perl
This Powershell snippet below will search through C:\whatever and return the empty subdirectories
$a = Get-ChildItem C:\whatever -recurse | Where-Object {$_.PSIsContainer -eq $True}
$a | Where-Object {$_.GetFiles().Count -eq 0} | Select-Object FullName
WARNING: The above will ALSO return all directories that contain subdirectories (but no files)!
This python code below will list all empty subdirectories
import os;
folder = r"C:\whatever";
for path, dirs, files in os.walk(folder):
if (dirs == files): print path

- 5,361
- 10
- 45
- 69

- 6,784
- 1
- 36
- 61
-
2I would say Powershell approach should be the one to be used by the OP. Do you imagine using a Unix abstraction layer/emulator if there's a Windows-based solution? ;) – Matías Fidemraizer Sep 02 '13 at 10:25
-
1Yes, I am working on both windows and unix and thus prefer solutions that work with both. Actually in the case where this issue came up I preferred the python solution. I just added the powershell way for completeness. I will sort it up though. – Udo Klein Sep 02 '13 at 10:28
The Powershell script in the accepted answer does not actually find truly empty folders (directories). It considers a folder with subfolders to be empty. Much of the blame lies on Microsoft, who wrote that script. Apparently, Microsoft considers a folder that contains subfolders to be empty. That explains a lot of things.
Here is a 1-line Powershell script that will actually return all empty folders. I define an empty folder to be a folder that is actually, um, empty.
(gci C:\Example -r | ? {$_.PSIsContainer -eq $True}) | ? {$_.GetFiles().Count + $_.GetDirectories().Count -eq 0} | select FullName
In the above example, replace C:\Example
with any path you would like to check. To check an entire drive, simple specify the root (e.g. C:\
for drive C
).

- 5,361
- 10
- 45
- 69
One can also call Win32 functions from Powershell, PathIsDirectoryEmptyW
will return true if Directory is empty.
$MethodDefinition = @’
[DllImport(“Shlwapi.dll”, CharSet = CharSet.Unicode)]
public static extern bool PathIsDirectoryEmptyW(string lpExistingDirName);
‘@
$Shlwapi = Add-Type -MemberDefinition $MethodDefinition -Name ‘Shlwapi’ -Namespace ‘Win32’ -PassThru
$a = Get-ChildItem C:\whatever -recurse | Where-Object {$_.PSIsContainer -eq $True}
$a | Where-Object {$Shlwapi::PathIsDirectoryEmptyW("$($_.FullName)")} | Select-Object FullName

- 4,111
- 1
- 25
- 24