Counting with PowerShell

How many files are stored on your computer? How many users have not logged on for a year? How many users use Active Sync? How many Pictures and Music Files are stored? All those questions can be answered by a single One-Liner in PowerShell. And there are many ways to do this. Choose your favourite.

Counting using Measure-Object

Measure-Object creates statistics. (count, average, sum, minimum and maximum values). We are looking for the count thing.

Example: Looking for the number of files in a specific folder

Get-ChildItem -Path C:\Data | Measure-Object


To get only the Count use Select-Object.

Get-ChildItem -Path C:\Data | Measure-Object | Select-Object Count


Counting using .count

I will use the same example as above. But now I place the command in brackets and use the .count method.

(Get-ChildItem -Path C:\Data).count


Counting using Group-Object

A more advanced option is using Group-Object. The Group-Object cmdlet displays the output in groups based on specified criterias. A table is returned. That is cool stuff, we can now search by properties and show the number of files by this property.

Get-ChildItem -Path C:\Data | Group-Object Extension


If you are only interested in the number and the type of the files run Group-Object with -NoElement.

Get-ChildItem -Path C:\Data | Group-Object Extension -NoElement


More useful Examples for Administrators

Muhammad Ali had a great line in the 70s when he was asked: “How many sit-ups do you do?”. He answered: “I don´t count my situps, i only start counting when it starts hurting, because then it really counts.”

If you feel pain when seeing the increasing number of orphaned user accounts in your organization then you should begin cleaning up. Then it really counts. 😉

How many Active Directory Users have not logged on to the domain for a year?

(Get-ADUser -Filter * -Properties LastLogonDate | ? {$_.lastlogondate -ne $null -and $_.lastlogondate -le ((get-date).adddays(-365))}).count

Count the number of Active Sync Users.

(Get-CASMailbox -Filter {hasactivesyncdevicepartnership -eq $true -and -not displayname -like "CAS_*"} | Get-Mailbox).count

Count your Domain Controllers.

Get-ADDomainController -Filter * | Measure-Object | Select Count

See also

For documenting purposes see also my article PowerShell: My top 10 commands for documenting and monitoring Active Directory

Categories: PowerShell

Tagged as: ,

1 reply »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.