prosource

폴더가 비어 있는지 Powershell 테스트

probook 2023. 4. 8. 08:40
반응형

폴더가 비어 있는지 Powershell 테스트

Powershell에서 디렉토리가 비어 있는지 테스트하려면 어떻게 해야 합니까?

숨겨진 파일 또는 시스템 파일에 관심이 없는 경우 테스트 경로를 사용할 수도 있습니다.

디렉토리에 파일이 있는지 확인하려면.\temp다음을 사용할 수 있습니다.

Test-Path -Path .\temp\*

또는 잠시 후:

Test-Path .\temp\*

이거 드셔보세요.

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

한다면$directoryInfo.count -eq 0디렉토리가 비어 있습니다.

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
}

모든 파일과 디렉토리를 가져와 디렉토리가 비어 있는지 확인하기 위해서만 카운트하는 것은 낭비입니다.사용하는 것이 훨씬 좋습니다.그물EnumerateFileSystemInfos

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

다음 방법을 사용할 수 있습니다..GetFileSystemInfos().Count디렉토리 수를 확인합니다.Microsoft 문서

$docs = Get-ChildItem -Path .\Documents\Test
$docs.GetFileSystemInfos().Count
#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}

심플한 어프로치

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

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

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

파이프용 라인 1개,GetFileSystemInfos().Count테스트의 경우:

gci -Directory | where { !@( $_.GetFileSystemInfos().Count) } 

항목이 없는 디렉토리가 모두 표시됩니다.결과:

Directory: F:\Backup\Moving\Test

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----         5/21/2021   2:53 PM                Test [Remove]
d-----         5/21/2021   2:53 PM                Test - 1   
d-----         5/21/2021   2:39 PM                MyDir [abc]
d-----         5/21/2021   2:35 PM                Empty

이름에 괄호가 포함되어 있어 엣지 케이스 문제가 있었기 때문에 이 글을 올렸습니다.[ ]; 실패는 다른 메서드를 사용하여 출력을 파이프로 연결한 경우입니다.Remove-Item괄호로 둘러싸인 디렉토리명이 누락되었습니다.

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

위의 코드는 먼저 폴더에 액세스를 시도합니다.오류가 발생하면 오류가 발생했음을 출력합니다.오류가 없으면 "폴더에 액세스할 수 있습니다"라고 말한 후 비어 있는지 확인합니다.

기존 답변 중 몇 가지를 검토하고 약간의 실험을 한 후, 다음과 같은 접근방식을 사용하게 되었습니다.

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)그런 다음 속성으로 인해 디렉토리, 숨김 파일 또는 "일반" 파일** 등의 내용을 확인합니다.d,h,그리고.a,각각 다음과 같다.

사용법은 충분히 명확해야 합니다.

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% 확신할 수는 없지만, 어떤 경우에도 모든 파일이 포함됩니다. 문서에는 숨겨진 파일이 표시되어 있고, 시스템 파일도 표시되어야 한다고 생각하기 때문에, 그 자체로 「일반」파일이라고 생각됩니다. 위의 함수에서 삭제하면 숨겨진 파일은 찾을 수 있지만 다른 파일은 찾을 수 없습니다.

언급URL : https://stackoverflow.com/questions/10550128/powershell-test-if-folder-empty

반응형