Powershell测试文件夹是否为空

Col*_*nic 58 powershell

在Powershell中,如何测试目录是否为空?

JPB*_*anc 56

如果您对隐藏文件或系统文件不感兴趣,也可以使用Test-Path

要查看目录中.\temp是否存在文件,您可以使用:

Test-Path -Path .\temp\*
Run Code Online (Sandbox Code Playgroud)

或者很快:

Test-Path .\temp\*
Run Code Online (Sandbox Code Playgroud)

  • +1 这样一种简洁的检查方式。这应该被接受的答案。顺便说一句,你甚至可以做`Test-Path .\temp\*`(没有`-Path`)。 (3认同)
  • 不确定是否理解您的问题,因为如果 temp 中存在目录,则 temp 不再被视为空。 (2认同)

Boe*_*ckm 45

试试这个...

$directoryInfo = Get-ChildItem C:\temp | Measure-Object
$directoryInfo.count #Returns the count of all of the objects in the directory
Run Code Online (Sandbox Code Playgroud)

如果$directoryInfo.count -eq 0,则您的目录为空.

  • 默认情况下,`gci`不会显示隐藏文件,因此您需要`-force`参数来确保该目录真正为空. (6认同)
  • 我们必须找到每个文件吗?这可能很耗时. (5认同)

Mui*_*ota 15

为了防止枚举c:\ Temp下的每个文件(这可能很耗时),我们可以做这样的事情:

if((Get-ChildItem c:\temp\ -force | Select-Object -First 1 | Measure-Object).Count -eq 0)
{
   # folder is empty
}
Run Code Online (Sandbox Code Playgroud)


Joe*_*oey 5

filter Test-DirectoryEmpty {
    [bool](Get-ChildItem $_\* -Force)
}
Run Code Online (Sandbox Code Playgroud)