programing

PowerShell에서 디렉터리 제외

codeshow 2023. 9. 4. 20:49
반응형

PowerShell에서 디렉터리 제외

PowerShell 검색에서 모든 디렉터리를 제외합니다.둘다요.FileInfo그리고.DirectoryInfo들어있다Attributtes정확히 내가 원하는 속성인 것처럼 보이지만, 나는 그것을 기반으로 필터링하는 방법을 찾을 수 없었다. 둘 다.

ls | ? { $_.Attributes -ne 'Direcory' }
ls | ? { $_.Attributes -notcontains 'Direcory' }

작동하지 않았습니다.어떻게 해야 하나요?

사용할 수 있습니다.PSIsContainer속성:

gci | ? { !$_.PSIsContainer }

접근 방식도 효과적이지만 다음과 같이 해야 합니다.

gci | ? { !($_.Attributes -band [IO.FileAttributes]::Directory) }

속성이 열거형 및 비트마스크이기 때문입니다.

또는 다음과 같은 다른 접근 방식을 참조하십시오.

gci | ? { "$($_.Attributes)" -notmatch "Directory" }

이렇게 하면 속성이 문자열("Directory, ReparsePoint"처럼 보일 수 있음)로 변환되고 문자열에서 다음을 사용할 수 있습니다.-notmatch교환입니다.

PowerShell v3에는 드디어-Directory에 대한 매개 변수.Get-ChildItem:

Get-ChildItem -Directory
gci -ad

PowerShell에서 디렉터리 제외:

Get-ChildItem | Where-Object {$_ -isnot [IO.DirectoryInfo]}

또는 간결하지만 버전을 읽기가 더 어렵습니다.

gci | ? {$_ -isnot [io.directoryinfo]}

그의 통찰력 있는 논평에 대한 공로는 @Joey에게 있습니다.-is연산자 :)

하지만

Get-ChildItem은 단순히 파일과 디렉토리 이상을 반환할 수 있기 때문에 제외하면 예기치 않은 결과를 초래할 수 있기 때문에 기술적으로 파일만 포함하거나 디렉토리만 포함하는 것을 선호합니다 :)

파일만 포함:

Get-ChildItem | Where-Object {$_ -is [IO.FileInfo]}

또는:

gci | ? {$_ -is [io.fileinfo]}

디렉터리만 포함:

Get-ChildItem | Where-Object {$_ -is [IO.DirectoryInfo]}

또는:

gci | ? {$_ -is [io.directoryinfo]}

디렉터리 유형을 직접 확인하여 디렉터리를 필터링할 수도 있습니다.

ls | ?{$_.GetType() -ne [System.IO.DirectoryInfo]}

디렉터리는 시스템 유형의 하위 항목(orl 또는 dir)으로 반환됩니다.IO.디렉토리정보 및 파일은 시스템 유형입니다.IO.FileInfo.Powershell에서 유형을 리터럴로 사용할 때는 괄호 안에 넣어야 합니다.

다양한 접근 방식에 대한 타이밍, 짧은 dir의 경우 5000회 반복 시간 / System32 dir의 경우 25회 반복 시간.측정은 다음을 사용하여 수행됩니다.

(measure-command { for ($i=0;$i -lt 5e3;$i++) {       
  $files= gci | ? { !$_.PSIsContainer }   # this is target to measure
} } ).totalmilliseconds

가장 느린 것부터 가장 빠른 것까지의 결과(모든 라인의 최종 결과가 동일함):

$files= gi *.* | ? { !$_.PSIsContainer }  #5000 iterations / 25long = 15.2sec / 22s
$files= foreach ($file in gi *.*) { if ($file.mode -notmatch 'd') { $file } }   # 11.8s / 20s
$files= gci | ? { !($_.Attributes -band [IO.FileAttributes]::Directory) }  # 8.9s  /  10.7s
$files= Get-ChildItem | Where-Object {$_.mode -notmatch 'd'}  # 8.8s  / 10.6s
$files= gci | ? { !$_.PSIsContainer }  # 7.8s  / 9.8s
$files= Get-ChildItem | ? {$_ -isnot [IO.DirectoryInfo]}  # 7.6s  /  9.6s
$files= gci | Where-Object {$_ -is [IO.FileInfo]}  # 7.6s  / 9.6s
$files= foreach ($file in gci *.*) { if ($file.mode -notmatch 'd') { $file } }    #7.3s  / 12.4s
$files= @( foreach ($file in gci) { if ($file.mode -notmatch 'd') { $file } } ) #3.7s  /  6.4s
$files= foreach ($file in gci) { if ($file.mode -notmatch 'd') { $file } }  # 3.7s  /  6.4s

"*"를 지정합니다.프로세스 시간이 거의 두 배가 됩니다.그렇기 때문에 매개 변수가 없는 GCI가 *.* 매개 변수를 사용해야 하는 GI보다 빠릅니다.

언급URL : https://stackoverflow.com/questions/1248634/exclude-directories-in-powershell

반응형