PowerShell 스크립트를 사용하여 Windows에서 빈 디렉터리를 찾는 방법


8

Windows에서 빈 디렉터리를 찾기 위해 사용하는 명령은 무엇입니까?

일부 폴더에는 숨겨진 폴더가 포함될 수 있습니다. .svn 또는 .settings하지만 여전히 빈 폴더로 처리해야합니다.


어떤 Windows 버전을 실행하고 있습니까?
Windos

답변:


12

내가 생각할 수있는 가장 쉬운 방법은 작은 것입니다. PowerShell 스크립트 . Windows 7을 실행중인 경우 Microsoft.com을 방문하여 다운로드 및 설치하지 않은 경우 이미 설치되어 있어야합니다. 이 링크는 자세한 설명을 제공하지만 작업의 jist가 여기에 포함되어 있습니다.

PowerShell을 열고 다음을 입력하십시오.

(gci C:\Scripts -r | ? {$_.PSIsContainer -eq $True}) | ? {$_.GetFiles().Count -eq 0} | select FullName

C : \ Scripts를 검색하려는 항목으로 변경하십시오. 전체 드라이브를 확인하려면 C : \로만 설정할 수도 있습니다.

이렇게하면 다음과 같은 결과를 얻을 수 있습니다 (C : \ Scripts 아래의 빈 디렉토리입니다).

FullName
------- 
C:\Scripts\Empty 
C:\Scripts\Empty Folder 2 
C:\Scripts\Empty\Empty Subfolder 
C:\Scripts\New Folder\Empty Subfolder Three Levels Deep

PowerShell을 조금만 살펴보면 원하는 경우 빈 폴더를 자동으로 삭제하는 방법을 알아낼 수있을 것이라고 확신합니다 (반대하는 경우에도 권장합니다).

편집하다 : 리처드가 주석에서 언급했듯이, 정말로 빈 디렉토리를 사용하려면 :

(gci C:\Scripts -r | ? {$_.PSIsContainer -eq $True}) | ?{$_.GetFileSystemInfos().Count -eq 0} | select FullName

Windows Vista 사용
Joshua

Vista 용 PowerShell은 여기에서 다운로드 할 수 있습니다. microsoft.com/download/en/details.aspx?id=23200
Windos

7
참고 : 해당 파이프 라인은 파일이 없지만 다른 폴더를 포함하는 폴더를 찾습니다. 완전히 비어있는 폴더를 사용하려면 파이프의 세 번째 요소를 다음과 같이 변경하십시오. ?{$_.GetFileSystemInfos().Count -eq 0}.
Richard

1
@ 조슈아, "C : \ Scripts"를 검색 할 위치로 변경하지 않았으므로 "존재하지 않는 경로 'C : \ Scripts'를 찾을 수 없습니다."라는 오류 메시지가 나타납니다. 그것은 라인의 시작 부분에 맞습니다.
Windos

1
@ 여호수아, Richards comment (이 글의 세 번째 글)와 답을 편집 해 주시겠습니까? 그러면 파일이없고 하위 디렉토리가없는 디렉토리 (예 : 리프 노드) 만 제공됩니다.
Windos

2

다음은 한 줄의 코드로이를 달성하는 가장 쉬운 방법입니다. 현재 위치의 빈 디렉토리를 나열합니다. 재귀가 필요한 경우 매개 변수 -Recurse 에 대한 호출에 추가 될 수 있음 Get-ChildItem.

Get-ChildItem -Directory | Where-Object { $_.GetFileSystemInfos().Count -eq 0 }

별칭이있는 짧은 버전 :

dir -Directory | ? {$_.GetFileSystemInfos().Count -eq 0 }

또는 매개 변수화 된 PowerShell 함수로 (필자의 PowerShell 시작 프로파일에 추가했습니다) :

Function Get-EmptyDirectories($basedir) { 
    Get-ChildItem -Directory $basedir | Where-Object { $_.GetFileSystemInfos().Count -eq 0 }
}

그런 다음 파이핑을 포함하여 다른 PowerShell 함수로 호출 할 수 있습니다. 예를 들어,이 호출은 시스템 임시 디렉토리에있는 모든 빈 디렉토리를 삭제합니다.

Get-EmptyDirectories $env:TMP | del


1

고마워, 나는 이것을 대본의 기초로 사용했다. 빈 폴더를 삭제하려고했지만 시도하고 싶었습니다. Where-Object {$_.GetFiles().Count -eq 0} 비어 있지 않은 하위 디렉토리가있는 폴더는 삭제됩니다. DO WHILE 루프를 사용하여 파일이나 폴더가없는 폴더를 제거한 다음 다시 루프를 실행하고 트리의 끝에 도달 할 때까지 다시 확인했습니다.

$Datefn=Get-Date -format M.d.yyyy_HH.mm.ss
#Set The File Name for the log file
$DelFileName = $Datefn
#Set The File Ext for the log file
$DelFileExt = " - Old Files" + ".log"
#Set The File Name With Ext for the log file
$DelFileName = $DelFileName + $DelFileExt
#Set Log Path
$LogPath = [Environment]::GetFolderPath("Desktop")
$Path = 'Q:\'
$NumDays = 365
Get-ChildItem -Path $Path -Exclude DCID.txt,*.exe -Recurse | Where-Object {$_.lastwritetime -lt`
(Get-Date).addDays(-$NumDays) -and $_.psiscontainer -eq $false} |
    ForEach-Object  {
        $properties = @{`
            Path = $_.Directory`
            Name = $_.Name
            DateModified = $_.LastWriteTime
            Size = $_.Length / 1GB  }
    New-Object PSObject -Property $properties | select Path,Name,DateModified, Size
    } |
    Out-File "$LogPath\$DelFileName"
<#
#Removes the files found
Get-ChildItem -Path $Path -Exclude DCID.txt,*.exe -Recurse | Where-Object {$_.lastwritetime -lt`
(Get-Date).addDays(-365) -and $_.psiscontainer -eq $false} | Remove-Item -Recurse -Force
#Removes empty folders
DO {
$a = (Get-ChildItem $Path -Recurse | Where-Object {$_.PSIsContainer -eq $true}) | Where-Object`
{$_.GetFileSystemInfos().Count -eq 0} | Select-Object Fullname
$a
(Get-ChildItem $Path -Recurse | Where-Object {$_.PSIsContainer -eq $true}) | Where-Object`
{$_.GetFileSystemInfos().Count -eq 0} | Remove-Item -Force
}
WHILE ($a -ne $null)
#>

1

이 시도

Get-ChildItem C:\Scripts -Recurse -Directory | Where-Object {!$_.GetFileSystemInfos().Count}

수는 0이 아니며 디렉토리가 완전히 비어 있거나 완전히 다른 빈 폴더를 보유하고 있음을 의미하지는 않습니다

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.