在 Windows 中查找所有空目录(文件夹)

问题描述 投票:0回答:3

如何在 Windows 中查找所有空目录?对于 Unix,存在find。所以有一个开箱即用的解决方案。使用 Windows 的最佳解决方案是什么?

windows directory is-empty
3个回答
1
投票

到目前为止我找到了几个解决方案:

  1. 使用Powershell查找空目录
  2. 安装 Cygwin 或 Gnu Findtools 并遵循 unix 方法。
  3. 使用 Python 或其他一些脚本语言,例如珀尔

下面的这个 Powershell 片段将搜索 C:\whatever 并返回空子目录

$a = Get-ChildItem C:\whatever -recurse | Where-Object {$_.PSIsContainer -eq $True}
$a | Where-Object {$_.GetFiles().Count -eq 0} | Select-Object FullName

警告:以上内容还将返回所有包含子目录(但不包含文件)的目录!

下面的 python 代码将列出所有空子目录

import os;
folder = r"C:\whatever";

for path, dirs, files in os.walk(folder):
    if (dirs == files): print path

0
投票

接受的答案中的 Powershell 脚本实际上并没有找到真正的空文件夹(目录)。它认为具有子文件夹的文件夹为空。大部分责任都归咎于编写该脚本的微软。显然,Microsoft 认为包含子文件夹的文件夹是空的。 这解释了很多事情。

这是一个 1 行 Powershell 脚本,它实际上会返回所有空文件夹。我将一个空文件夹定义为一个实际上是空的文件夹。

(gci C:\Example -r | ? {$_.PSIsContainer -eq $True}) | ? {$_.GetFiles().Count + $_.GetDirectories().Count -eq 0} | select FullName

在上面的示例中,将

C:\Example
替换为您要检查的任何路径。要检查整个驱动器,只需指定根目录(例如,
C:\
代表驱动器
C
)。


0
投票

也可以从 Powershell 调用 Win32 函数,

PathIsDirectoryEmptyW
如果目录为空,将返回 true。

$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
© www.soinside.com 2019 - 2024. All rights reserved.