Reputation: 6912
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?
Upvotes: 2
Views: 2015
Reputation: 134
I found solution on another source https://superuser.com/a/1146262
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
Upvotes: 0
Reputation: 4237
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
Upvotes: 0
Reputation: 5833
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
).
Upvotes: 2
Reputation: 6912
I found several solutions so far:
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
Upvotes: 2