如何从指定根路径查找所有空目录及子目录
获取指定路径下所有空目录(含子目录)的方法
Linux/macOS 平台
仅列出空目录
使用find命令精准筛选:
find /目标路径 -type d -empty
参数说明:
-type d:限定查找对象为目录-empty:筛选无任何文件或子目录的空目录
列出并直接删除(谨慎操作)
确认列表无误后,可直接联动删除:
find /目标路径 -type d -empty -delete
提示:务必先单独执行列出命令确认结果,避免误删重要目录。
Windows 平台
PowerShell 方案
仅列出空目录
Get-ChildItem -Path "C:\目标路径" -Recurse -Directory | Where-Object { $_.GetFiles().Count -eq 0 -and $_.GetDirectories().Count -eq 0 }
逻辑:递归遍历目录,筛选出既无文件也无子目录的空目录。
列出并删除
Get-ChildItem -Path "C:\目标路径" -Recurse -Directory | Where-Object { $_.GetFiles().Count -eq 0 -and $_.GetDirectories().Count -eq 0 } | Remove-Item
CMD 命令行方案
仅列出空目录
for /r "C:\目标路径" /d %d in (*) do @dir /b "%d" | findstr "^" >nul || echo %d
逻辑:递归遍历所有子目录,检查目录内是否有内容,无内容则输出路径。
列出并删除
将上述命令中的echo %d替换为rd "%d"即可:
for /r "C:\目标路径" /d %d in (*) do @dir /b "%d" | findstr "^" >nul || rd "%d"
内容的提问来源于stack exchange,提问作者alboforlizo
相关产品推荐
相关产品推荐

