[powershell-2.0] PowerShell을 사용하여 폴더의 항목 계산

주어진 폴더 ( c:\MyFolder) 에있는 총 항목 수 (파일과 폴더 모두)를 제공하는 매우 간단한 PowerShell 스크립트를 작성하려고합니다 . 내가 한 일은 다음과 같습니다.

Write-Host ( Get-ChildItem c:\MyFolder ).Count;

문제는 항목이 1 개 또는 0 개이면 명령이 작동하지 않는다는 것입니다. 아무 것도 반환하지 않습니다.

어떤 아이디어?



답변

당신은 Measure-Object물건을 세는 데 사용해야 합니다. 이 경우 다음과 같습니다.

Write-Host ( Get-ChildItem c:\MyFolder | Measure-Object ).Count;

또는 너무 길면

Write-Host ( dir c:\MyFolder | mo).Count;

PowerShell 4.0에서는 measure대신 별칭을 사용하십시오.mo

Write-Host (dir c:\MyFolder | measure).Count;


답변

마침내이 링크를 찾았습니다.

https://blogs.perficient.com/microsoft/2011/06/powershell-count-property-returns-nothing/

음, 이것은 디렉토리에 파일이 하나뿐이기 때문에 정확하게 발생하는 기이 한 것으로 밝혀졌습니다. 일부 검색 결과이 경우 PowerShell은 배열 대신 스칼라 개체를 반환합니다. 이 개체에는 count 속성이 없으므로 검색 할 항목이 없습니다.

해결책-PowerShell이 @기호가 있는 배열을 반환하도록 강제합니다 .

Write-Host @( Get-ChildItem c:\MyFolder ).Count;


답변

프로세스 속도를 높여야한다면 (예 : 30k 이상의 파일 계산) 다음과 같이 할 것입니다 ..

$filepath = "c:\MyFolder"
$filetype = "*.txt"
$file_count = [System.IO.Directory]::GetFiles("$filepath", "$filetype").Count


답변

파일 만

Get-ChildItem D:\ -Recurse -File | Measure-Object | %{$_.Count}

폴더 만

Get-ChildItem D:\ -Recurse -Directory | Measure-Object | %{$_.Count}

양자 모두

Get-ChildItem D:\ -Recurse | Measure-Object | %{$_.Count}


답변

PowerShell 2.0의 디렉터리에있는 파일을 재귀 적으로 계산

ls -rec | ? {$_.mode -match 'd'} | select FullName,  @{N='Count';E={(ls $_.FullName | measure).Count}}


답변

powershell에서이 명령 숫자를 찾기 위해 여러 명령을 사용할 수 있습니다. Get-Alias;

따라서 사용할 수있는 캠 맨드는 다음과 같습니다.

write-host (ls MydirectoryName).Count

또는

write-host (dir MydirectoryName).Count

또는

write-host (Get-ChildrenItem MydirectoryName).Count


답변

폴더에있는 특정 파일 형식의 수를 계산합니다. 예제는 F : 드라이브에있는 mp3 파일을 계산하는 것입니다.

( Get-ChildItme F: -Filter *.mp3 - Recurse | measure ).Count

6.2.3에서 테스트되었지만> 4에서 작동합니다.