code

폴더가 비어있는 경우 Powershell 테스트

codestyles 2021. 1. 6. 08:22
반응형

폴더가 비어있는 경우 Powershell 테스트


Powershell에서 디렉터리가 비어 있는지 어떻게 테스트합니까?


이 시도...

$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\*

또는 곧 :

Test-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에 추가하기 만하면 디렉토리 경로가 $ 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
    }

모든 파일과 디렉토리를 가져 와서 디렉토리가 비어 있는지 확인하기 위해서만 세는 것은 낭비입니다. .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 (-Not (Test-Path .\temp*) 
{
 #do your stuff here
} 

-Not파일이있을 때 'if'를 입력하려면 제거 할 수 있습니다.


빈 폴더 제거의 예 :

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

    $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"
    }

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

Getting a count from Get-ChildItem can provide false results because an empty folder or error accessing a folder could result in a 0 count.

The way I check for empty folders is to separate out errors:

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

The above code first tries to acces the folder. If an error occurs, it outputs that an error occurred. If there was no error, state that "Folder can be accessed", and next check if it's empty.


After looking into some of the existing answers, and experimenting a little, I ended up using this approach:

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

This will first check for a valid directory (Test-Path ($dir)). It will then check for any contents including any directories, hidden file, or "regular" files** due to the attributes d, h, and a, respectively.

Usage should be clear enough:

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

...or alternatively:

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

** Actually I'm not 100% certain what the defined effect of of a is here, but it does in any case cause all files to be included. The documentation states that ah shows hidden files, and I believe as should show system files, so I'm guessing a on it's own just shows "regular" files. If you remove it from the function above, it will in any case find hidden files, but not others.

ReferenceURL : https://stackoverflow.com/questions/10550128/powershell-test-if-folder-empty

반응형