Powershelltesting如果文件夹为空

在Powershell中,如何testing一个目录是否为空?

尝试这个…

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

如果$directoryInfo.count -eq 0 ,那么你的目录是空的。

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

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

 Test-Path -Path .\temp\* 

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

 if((Get-ChildItem c:\temp\ -force | Select-Object -First 1 | Measure-Object).Count -eq 0) { # folder is empty } 
 filter Test-DirectoryEmpty { [bool](Get-ChildItem $_\* -Force) } 

一条线:

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

只要添加到JPBlanc,如果目录path是$ DirPath,这个代码也适用于包括方括号字符的path。

  # 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 } 

获取所有文件和目录并仅计算它们以确定目录是否为空是很浪费的。 更好地使用.NET EnumerateFileSystemInfos

 $directory = Get-Item -Path "c:\temp" if (!($directory.EnumerateFileSystemInfos() | select -First 1)) { "empty" } 
 ################################################# # 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 } 

删除空文件夹的示例:

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

简单的方法

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

你可以删除-Not如果你想要input“如果”文件时出现