Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 859
HydroPowerDeveloper Avatar asked Feb 05 '13 18:02

HydroPowerDeveloper


People also ask

How do I count files in a directory in PowerShell?

If you want to count the files and folders inside that directory, run this command: (Get-ChildItem | Measure-Object). Count.

How do I count items in PowerShell?

You can use Measure-Object to count objects or count objects with a specified Property. You can also use Measure-Object to calculate the Minimum, Maximum, Sum, StandardDeviation and Average of numeric values. For String objects, you can also use Measure-Object to count the number of lines, words, and characters.

How do I count files in a folder and subfolders?

Use File Explorer Open the folder and select all the subfolders or files either manually or by pressing CTRL+A shortcut. If you choose manually, you can select and omit particular files. You can now see the total count near the left bottom of the window. Repeat the same for the files inside a folder and subfolder too.


1 Answers

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; 
like image 84
Stanley De Boer Avatar answered Sep 20 '22 12:09

Stanley De Boer