Count items in a folder with PowerShell

后端 未结 7 1252
闹比i
闹比i 2020-12-01 04:10

I\'m trying to write a very simple PowerShell script to give me the total number of items (both files and folders) in a given folder (c:\\MyFolder). Here\'s wh

相关标签:
7条回答
  • 2020-12-01 04:28

    In powershell you can to use severals commands, for looking for this commands digit: Get-Alias;

    So the cammands the can to use are:

    write-host (ls MydirectoryName).Count
    

    or

    write-host (dir MydirectoryName).Count
    

    or

    write-host (Get-ChildrenItem MydirectoryName).Count
    
    0 讨论(0)
  • 2020-12-01 04:30

    I finally found this link:

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

    Well, it turns out that this is a quirk caused precisely because there was only one file in the directory. Some searching revealed that in this case, PowerShell returns a scalar object instead of an array. This object doesn’t have a count property, so there isn’t anything to retrieve.

    The solution -- force PowerShell to return an array with the @ symbol:

    Write-Host @( Get-ChildItem c:\MyFolder ).Count;
    
    0 讨论(0)
  • 2020-12-01 04:32

    Only Files

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

    Only Folders

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

    Both

    Get-ChildItem D:\ -Recurse | Measure-Object | %{$_.Count}
    
    0 讨论(0)
  • 2020-12-01 04:33

    You should use Measure-Object to count things. In this case it would look like:

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

    or if that's too long

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

    and in PowerShell 4.0 use the measure alias instead of mo

    Write-Host (dir c:\MyFolder | measure).Count;
    
    0 讨论(0)
  • 2020-12-01 04:41

    Recursively count files in directories in PowerShell 2.0

    ls -rec | ? {$_.mode -match 'd'} | select FullName,  @{N='Count';E={(ls $_.FullName | measure).Count}}
    
    0 讨论(0)
  • 2020-12-01 04:48

    If you need to speed up the process (for example counting 30k or more files) then I would go with something like this..

    $filepath = "c:\MyFolder"
    $filetype = "*.txt"
    $file_count = [System.IO.Directory]::GetFiles("$filepath", "$filetype").Count
    
    0 讨论(0)
提交回复
热议问题