Counting Objects in PowerShell
-
Use the
Count
Method in PowerShell to Count Objects -
Count in PowerShell Using the
Measure-Object
Command

There are several reasons wherein we may want to count objects in PowerShell. Whatever we need to count in PowerShell, you can use either the Count
operator or the Measure-Object
cmdlet.
This article will discuss different examples of how to count with both methods.
Use the Count
Method in PowerShell to Count Objects
Syntax:
(PSObject).Count
We can access the PowerShell Count
operator by wrapping the object in parentheses (()
). Then, add a period (.
), followed by the count.
For example, we wanted to know how many files were in a folder. The initial step to counting files in a folder is to use the Get-ChildItem
cmdlet to return the files.
Example Command:
$filelist = Get-ChildItem -Path "C:\Temp\Scripts" | Where-Object { !($_.PSIsContainer) }
In the command above, we will save the Get-ChildItem
cmdlet’s in a variable called $filelists
. In the second part of the command, we can pipe the final output of the Get-ChildItem
cmdlet to the Where-Object
command.
The Where-Object
cmdlet has !
in front of $_.PSIsContainer
– this tells Where-Object
to return all objects except folders. Finally, run the command below to count the number of files in a folder.
Example Command:
$filelist.Count
Output:
37
Remember that the Count
operator will always be a sub-property of any PowerShell object.
Count in PowerShell Using the Measure-Object
Command
Run the following command to see the full syntax of the Measure-Object
command.
Command:
Get-Help Measure-Object
We should pipe the result to the Measure-Object
cmdlet and specify the -Character
parameter to count in Windows PowerShell.
Example Command:
"654321" | Measure-Object -Character
Output:
Lines Words Characters Property
----- ----- ---------- --------
6
Another way to run the command is to specify the string 654321
with the InputObject
variable instead of piping it.
Example Command:
Measure-Object -InputObject "654321" -Character
Both characters will produce an output of six.
Output:
Lines Words Characters Property
----- ----- ---------- --------
6
Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.
LinkedInRelated Article - PowerShell Object
- Nested ForEach-Object and Where-Object in PowerShell
- PowerShell Sort Object
- Filter and Isolate PowerShell Objects
- Determine if Two Objects Are Identical in PowerShell
- Show All Properties of a PowerShell Object