PoshTip #29 – How to count objects in PowerShell?

PoshTip #29 – How to count objects in PowerShell?

The Measure-Object cmdlet gives us a great way to count objects. For example, if we want to count files and directories in the current directory, just use the following command:

PS > gci | Measure-Object


Count    : 17
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

You can use the following syntax:

PS > (gci | Measure-Object).count
17

So let’s confirm:

PS C:\Users\Nicolas> dir


    Directory: C:\Users\Nicolas


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       19.06.2016     00:29                .gimp-2.8
d-----       13.06.2016     20:41                .thumbnails
d-r---       02.07.2016     10:31                Contacts
d-r---       02.07.2016     10:31                Desktop
d-r---       02.07.2016     10:31                Documents
d-----       15.05.2016     22:39                dir1
d-r---       09.07.2016     16:07                Downloads
d-r---       02.07.2016     10:31                Favorites
d-----       14.05.2016     16:32                foo
d-r---       02.07.2016     10:31                Links
d-r---       02.07.2016     10:31                Music
d-r---       15.05.2016     19:00                OneDrive
d-r---       02.07.2016     10:31                Pictures
d-r---       02.07.2016     10:31                Saved Games
d-r---       02.07.2016     10:31                Searches
d-r---       02.07.2016     10:31                Videos
-a----       15.05.2016     22:40              7 File

You can use the Measure-Object cmdlet with Get-Alias:

PS > get-alias | measure


Count    : 155
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

You can count your environment variables:

PS > cd env:
PS Env:\> gci | measure


Count    : 37
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

 

Thanks for reading! You can follow me on Twitter @PrigentNico

About Nicolas 282 Articles
I work as an IT Production Manager, based in Paris (France) with a primary focus on Microsoft technologies. I have 10 years experience in administering Windows Servers. . I am a Microsoft MVP for Cloud & Datacenter Management. I also received the PowerShell Hero 2016 award by PowerShell.0rg. And finally, I am "MCSE: Cloud Platform and Infrastructure", "MCSA: Windows Servers", "Administering & Deploying SCCM", and CheckPoint CCSA certified.