Powershell: Count items in a folder with PowerShell

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 what I've done:

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

The problem is, that if I have 1 or 0 items, the command does not work---it returns nothing.

Any ideas?


Solution 1:

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;

Solution 2:

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;

Solution 3:

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

Solution 4:

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}

Solution 5:

You can also use an alias

(ls).Count