Powershell测试文件夹是否为空

时间:2012-05-11 11:03:41

标签: powershell

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

15 个答案:

答案 0 :(得分:48)

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

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

Test-Path -Path .\temp\*

或者很快:

Test-Path .\temp\*

答案 1 :(得分:41)

试试这个......

$directoryInfo = Get-ChildItem C:\temp | Measure-Object
$directoryInfo.count #Returns the count of all of the files in the directory

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

答案 2 :(得分:10)

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

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

答案 3 :(得分:3)

filter Test-DirectoryEmpty {
    [bool](Get-ChildItem $_\* -Force)
}

答案 4 :(得分:3)

一行:

if( (Get-ChildItem C:\temp | Measure-Object).Count -eq 0)
{
    #Folder Empty
}

答案 5 :(得分:1)

只需添加到JPBlanc,如果目录路径是$ DirPath,则此代码也适用于包含方括号字符的路径。

    # Make square bracket non-wild card char with back ticks
    $DirPathDirty = $DirPath.Replace('[', '`[')
    $DirPathDirty = $DirPathDirty.Replace(']', '`]')

    if (Test-Path -Path "$DirPathDirty\*") {
            # Code for directory not empty
    }
    else {
            # Code for empty directory
    }

答案 6 :(得分:1)

获取所有文件和目录并计算它们以确定目录是否为空是一种浪费。使用.NET EnumerateFileSystemInfos

要好得多
$directory = Get-Item -Path "c:\temp"
if (!($directory.EnumerateFileSystemInfos() | select -First 1))
{
    "empty"
}

答案 7 :(得分:1)

#################################################
# Script to verify if any files exist in the Monitor Folder
# Author Vikas Sukhija 
# Co-Authored Greg Rojas
# Date 6/23/16
#################################################


################Define Variables############ 
$email1 = "yourdistrolist@conoso.com" 
$fromadd = "yourMonitoringEmail@conoso.com" 
$smtpserver ="mailrelay.conoso.com" 

$date1 = get-date -Hour 1 -Minute 1 -Second 1
$date2 = get-date -Hour 2 -Minute 2 -Second 2 

###############that needs folder monitoring############################ 


$directory = "C:\Monitor Folder"

$directoryInfo = Get-ChildItem $directory | Measure-Object
$directoryInfo.count


if($directoryInfo.Count -gt '0') 
{ 

#SMTP Relay address 
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer) 

#Mail sender 
$msg.From = $fromadd 
#mail recipient 
$msg.To.Add($email1) 
$msg.Subject = "WARNING : There are " + $directoryInfo.count + " file(s) on " + $env:computername +  " in " + " $directory 
$msg.Body = "On " + $env:computername + " files have been discovered in the " + $directory + " folder."
$smtp.Send($msg) 

} 

Else
      { 
    Write-host "No files here" -foregroundcolor Green 
      } 

答案 8 :(得分:1)

简单方法

if (-Not (Test-Path .\temp*) 
{
 #do your stuff here
} 

如果您想要输入' if&#39>,则可以删除-Not文件存在时

答案 9 :(得分:1)

删除空文件夹的示例:

IF ((Get-ChildItem "$env:SystemDrive\test" | Measure-Object).Count -eq 0) {
    remove-Item "$env:SystemDrive\test" -force
}

答案 10 :(得分:1)

    $contents = Get-ChildItem -Path "C:\New folder"
    if($contents.length -eq "") #If the folder is empty, Get-ChileItem returns empty string
    {
        Remove-Item "C:\New folder"
        echo "Empty folder. Deleted folder"
    }
    else{
    echo "Folder not empty"
    }

答案 11 :(得分:1)

#Define Folder Path to assess and delete
$Folder = "C:\Temp\Stuff"

#Delete All Empty Subfolders in a Parent Folder
Get-ChildItem -Path $Folder -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

#Delete Parent Folder if empty
If((Get-ChildItem -Path $Folder -force | Select-Object -First 1 | Measure-Object).Count -eq 0) {Remove-Item -Path $CATSFolder -Force -Recurse}

答案 12 :(得分:0)

从Get-ChildItem获取计数可能会提供错误的结果,因为空文件夹或错误访问文件夹可能导致计数为0。

我检查空文件夹的方法是找出错误:

Try { # Test if folder can be scanned
   $TestPath = Get-ChildItem $Path -ErrorAction SilentlyContinue -ErrorVariable MsgErrTest -Force | Select-Object -First 1
}
Catch {}
If ($MsgErrTest) { "Error accessing folder" }
Else { # Folder can be accessed or is empty
   "Folder can be accessed"
   If ([string]::IsNullOrEmpty($TestPath)) { # Folder is empty
   "   Folder is empty"
   }
}

上面的代码首先尝试访问该文件夹。如果发生错误,则输出发生错误。如果没有错误,请指出“可以访问文件夹”,然后检查是否为空。

答案 13 :(得分:0)

研究了一些现有答案并进行了一些试验之后,我最终使用了这种方法:

function Test-Dir-Valid-Empty {
    param([string]$dir)
    (Test-Path ($dir)) -AND ((Get-ChildItem -att d,h,a $dir).count -eq 0)
}

这将首先检查有效目录Test-Path ($dir))。然后它将分别检查由于属性dha而引起的任何内容,包括目录,隐藏文件或“常规”文件**。

用法应足够清楚:

PS C_\> Test-Dir-Valid-Empty projects\some-folder
False 

...或者:

PS C:\> if(Test-Dir-Valid-Empty projects\some-folder){ "empty!" } else { "Not Empty." }
Not Empty.

** 实际上,我不确定100%a的定义效果在这里,但是在任何情况下都确实会导致所有文件都包含在内。文档指出ah显示隐藏文件,而我相信as应该显示系统文件,因此我猜测a本身仅显示“常规”文件。如果您从上面的功能中将其删除,无论如何它都会找到隐藏的文件,但是找不到其他文件。

答案 14 :(得分:0)

您可以使用方法.GetFileSystemInfos().Count检查目录数。 Microsoft Docs

$docs = Get-ChildItem -Path .\Documents\Test
$docs.GetFileSystemInfos().Count