Do you need to count objects using your PowerShell script? This guide covers several ways to do this.
Overview
There are so many reasons you may want to count objects in PowerShell. As an example, you may want to count error messages in an event log.
Moreover, you may want to count the number of files in a specific folder.
Whatever you need to count in PowerShell, you can use either the Count Operator or the Measure-Object Cmdlet. This guide teaches you different examples to demonstrate how to count with both methods.
Free tools Windows power users keep installed
One-click scans. No signup required.
#1 Best Overall
- Brilliant Color Illumination- With 11 unique backlights, choose the perfect ambiance for any mood. Adjust light speed and brightness among 5 levels for a comfortable environment, day or night. The double injection ABS keycaps ensure clear backlight and precise typing. From late-night tasks to immersive gaming, our mechanical keyboard enhances every experience
- Support Macro Editing: The K671 Mechanical Gaming Keyboard can be macro editing, you can remap the keys function, set shortcuts, or combine multiple key functions in one key to get more efficient work and gaming. The LED Backlit Effects also can be adjusted by the software(note: the color can not be changed)
- Hot-swappable Linear Red Switch- Our K671 gaming keyboard features red switch, which requires less force to press down and the keys feel smoother and easier to use. It's best for rpgs and mmo, imo games. You will get 4 spare switches and two red keycaps to exchange the key switch when it does not work.
- Full keys Anti-ghosting- All keys can work simultaneously, easily complete any combining functions without conflicting keys. 12 multimedia key shortcuts allow you to quickly access to calculator/media/volume control/email
- Professional After-Sales Service- We provide every Redragon customer with 24-Month Warranty , Please feel free to contact us when you meet any problem. We will spare no effort to provide the best service to every customer
Option 1: Count with the Count Operator
As already mentioned in the introduction, in this first section, I will teach you how to count with the Count Operator. The section starts with the syntax of the Count Operator.
Then, I share eight examples of different ways you can count with the Count Operator.
Syntax Of The PowerShell Count Operator
The syntax of the PowerShell Count Operator is:
(object to count).Count
The PowerShell Count Operator of an object can be accessed by wrapping the object in a bracket (). Then, add a period (.), followed by the word, count.
Example 1: Count Event Logs
The first application example is to show you how to count event logs.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →In this example, I want to count the number of error messages in the System log in the last 24 hours. I could run a single command but to make it easy to understand, I’ll break it down.
The first step is to save the last 24 hours in a variable, using the Get-Date command.
Here is the command…
$Last24Hours = (Get-Date).AddDays(-1)
Enter the command in PowerShell and press the enter key to run it.

Next, run the Get-EventLog command, pipe the output to the Where-Object command, and filter by Error. Save the result of the command in a variable called $ErrorLogCount.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problems$ErrorLogCount = Get-EventLog -LogName System -After $Last24Hours | Where-Object {$_.EntryType -eq "Error"}
If you wish to see a list of the error messages, run the variable, $ErrorLogCount.
$ErrorLogCount
Here are the commands in PowerShell…

Note that there are 5 error logs. This is easy to count – however if the result had hundreds of results, how do you count them?
Use PowerShell Count Operator! Here is the final command that counts the number of error logs in the result of the last command…
$ErrorLogCount.Count
And, as expected, the result is 4!

If you want to run the commands in a single command, here is the command…
(Get-EventLog -LogName System -After ((Get-Date).AddDays(-1)) | Where-Object {$_.EntryType -eq "Error"}).count
The result is the same…

Example 2: Count Files in a Folder
Another application of the PowerShell Count Method is to count the number of files in a folder. In this section, you will learn how to count files in a folder.
You will also learn how to count files in a folder and all sub-folders. Finally, I will teach you how to use the PowerShell Count Method to count files by date.
The first step to counting files in a folder is to use the Get-ChildItem command to return the files in a folder. In this example, I will save the result of the Get-ChildItem command in a variable called filelist.
$filelist = Get-ChildItem -Path "D:\PS-Tutorial" | Where-Object { !($_.PSIsContainer) }
In the second part of the command, I piped the output of the Get-ChildItem command to Where-Object. The Where-Object command has “!” in front of “$_.PSIsContainer” – this tells Where-Object to return all objects except folders.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Rank #2
- 1.RGB Side Lighting & Rainbow Effects Designed to impress, this backlit mechanical keyboard features 13 preset LED rainbow mixed lighting effects and stunning RGB side-edge illumination.(RGB only available for side lighting) Whether you're gaming in low light or showing off your setup, the immersive lighting transforms any desktop into a glowing command center. It's a visual upgrade to your mechanical gaming keyboard experience.
- 2.Premium Build with Full Size Metal Panel Crafted with a rugged metal top plate, this wired keyboard offers outstanding durability and a refined, tactile feel. Its solid construction ensures long-lasting reliability, even during intense gaming marathons. Ideal for serious gamers, this 104keys mechanical keyboard combines aesthetics and strength in a sleek full size computer keyboard design.
- 3. Flexible and Portable: Detachable USB Cable This wired mechanical keyboard comes equipped with a 1.8-meter detachable USB cable, offering easy portability and convenient cable management. Whether at home, at a LAN party, or traveling, this gaming keyboard ensures a stable and efficient keyboard setup every time. A must-have full size keyboard for gamers who value flexibility and performance in one package.
- 4. Smooth Red Switches & Full-Key Rollover Equipped with smooth, linear red switches, this mechanical gaming keyboard delivers ultra-responsive typing and fast actuation, perfect for both competitive gaming and everyday use. Full-key rollover ensures every keystroke is registered, even during rapid-fire actions. Enjoy seamless accuracy and quiet performance with this advanced mechanical keyboard.
- 5. Smart Shortcuts and Software Customization Access media controls, calculator, and other functions with FN+F1–F11 shortcuts. Take it further with customization software that lets you remap keys, record macros, and personalize lighting. Whether you’re playing or working, this 104 keys gaming mechanical keyboard adapts to your needs—offering unmatched versatility in a keyboard gaming environment.
Here is the command in PowerShell. To display the results saved in the variable, I ran the variable…

Finally, to count the number of files, wrap the result in the PowerShell Count Operator.
$filelist.Count
The result shows that there are 7 files.

Moving on, what if we want to count files in the folder and all subfolders? This requires simply adding the Recurse parameter to the Get-ChildItem bit of the command.
Here is the amended command that counts files in a folder and all its subfolders. This time, I ran the command as a single command.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
(Get-ChildItem -Path "D:\PS-Tutorial" -Recurse | Where-Object { !($_.PSIsContainer) }).Count
Here is the result with 7 files.

Example 3: Count Files in a Folder by Date
In the last section, I showed you how to count all files in a folder and subfolders.
In this section, I will show you how to count the number of files in a folder based on date.
To help you understand this example, run this command from our previous example.
$filelist = Get-ChildItem -Path "D:\PS-Tutorial" | Where-Object { !($_.PSIsContainer) }
Now, run the variable. The result shows that the files have a property called LastWriteTime.

The LastWriteTime property indicates the last time the file was created or updated. The implication is that we can include this property in the Where-Object filter – then, return only files that were updated or created on a specified date.
In this example, I want to count only files updated or created in the last 24 hours. So, I will need a date filter.
To generate the date filter, run the command below and save the result in a variable…
$Last24Hours = (Get-Date).AddDays(-1)
Then, use the variable, $Last24Hours as an additional filter in the Where-Object side of the previous command. Here is the updated command.
$filelist = Get-ChildItem -Path "D:\PS-Tutorial" -Recurse | Where-Object { (!($_.PSIsContainer)) -and ($_.LastWriteTime -ge $Last24Hours) }
The command introduces a new filter “$_.LastWriteTime -ge $Last24Hours”. This compares the LastWriteTime property of each file with the date saved in the $Last24Hours variable.
Then, any file with LastWriteTime greater than, or equal (ge) the date in the variable (last 24 hours), it will be returned in the result. However, any file with LastWriteTime that falls outside this range is removed.
Finally, to count the files in this folder and all its subfolders that were created or updated in the past 24 hours, use the PowerShell Count Operator command below:
$filelist.Count
Example 4: Count Objects in an Array
Recently, I updated our PowerShell Arrays article. In the latest update of the article, I created an array.
Recommended Free Tools
Rank #3
- Take your gaming skills to the next level: The Logitech G413 SE is a full-size keyboard with gaming-first features and the durability and performance necessary to compete
- PBT keycaps: Heat- and wear-resistant, this computer gaming keyboard features the most durable material used in keycap design
- Tactile mechanical switches: Uncompromising performance is always within reach with this wired gaming keyboard
- Premium color, material and finish: Elevate your gaming setup with this backlit keyboard featuring a sleek, black-brushed aluminum top case and white LED lighting
- 6-Key rollover anti-ghosting performance: Experience reliable key input with this anti-ghosting keyboard versus non-gaming mechanical keyboards
Here is the script that creates an array, saved in a variable, ArrayList.
$ArrayList = @("Document", "FileSystem", "D:\PS-Tutorial")
PowerShell Array has a Count Property. You can use this property the way we have used it in previous examples in this article.
Hence, to count the objects in the PowerShell array saved in the ArrayList variable, run the command below…
$ArrayList.Count
The result is 3 – confirming the number of objects in our array!

Option 2: Count with the Measure-Object Cmdlet
In the last section of this guide, you saw different ways to use PowerShell Count Operator to count objects. This section teaches you how to count objects with the Measure-Object Cmdlet.
As you can see in the examples in this section, the Measure-Object Cmdlet offers more options to count objects.
Before the examples though, let’s start with the syntax of the Measure-Object Cmdlet.
Syntax Of The Measure-Object Cmdlet
To see the full syntax of the Measure-Object Cmdlet, run the command below:
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteGet-Help Measure-Object
From the result of the command, the Measure-Object Cmdlet has two syntaxes. Here are the simplified versions of the syntaxes:
Measure-Object -Property -InputObject -Average -Maximum -Minimum -Sum
Measure-Object -Property -InputObject -Character -IgnoreWhiteSpace -Line -Word
You can use the first syntax to return average, min and max values of objects. However, if you want to count the number of characters, remove whitespaces, count lines, or word, use the second syntax.
In the following sub-sections, I will discuss various examples of how to use Measure-Object to count objects in PowerShell.
Example 1: Count Characters in a String
Most times, SysAdmins will need to count total number of items in a string or PowerShell object. However, in rare instances SysAdmins may come across PowerShell automatic tasks that require more granular counting.
Recommended Free Tools
For example, you may be required to count the number of characters in a string. In this example, I will teach you how to count the total number of characters in a string.
To be clear, a character is a single object like like 1, or a.
Let’s start with a very simple example, to count the number of characters in this string of numbers
123456
Obviously, there are six characters but how do we count the characters with PowerShell? The simple answer is to pipe the result to the Measure-Object command and specify the Character parameter.
Free tools Windows power users keep installed
One-click scans. No signup required.
Rank #4
- [75% Mechanical Keyboard with Rainbow Led Backlight] The 75% keyboard can save desk space. The detachable USB C cable and small mini size make it easy to portable for home/office/game use or business trips. The rainbow led backlit gaming mechanical keyboard provides you with cool visual effects. It offers 6 backlighting color and 20 backlighting modes to personalize your compact mechanical keyboards' appearance.
- [Hot Swappable Linear Mechanical Keyboard] This hotswap function can let you customize your gaming keyboard mechanical with different combination layout on keycaps and 3-pin switch. The red switches characterized for being linear and smoother, slight key sound with minimal resistance, but fast action without a tactile feel, and easy to tap the teclado mecanico.
- [Multi-Function Knob and Indicators] A multi-function knob in the upper right corner of the 75% percent keyboard enables you to adjust the sound level for fast, seamless and easy-to-use operation. Three indicator lights on the 75 percent keyboard give you a quicker overview of the tkl mechanical keyboard's status. The indicators from top to bottom refer to: Caps lock, Win lock, and Windows/Mac switch.
- [Full Key Anti-Ghosting Mechanical Keybaord] All keys non-conflict, the 75 percent keyboard allow multiple keys to work simultaneously, suitable for gamer, writer, programmer, typist etc. And this 75 percent mechanical keyboard is wide compatibilty, it adapt to pc, laptop, computer, compatibilty Win7/Win8/Win10/Win11, Mac OS10.10 or above.
- [Comfortable Ergonomic Keyboard] The wired mechanical keyboard adopts ABS keycap has better lightening effects while ergonomic stepped keycaps and two-stage support leg to black mechanical keyboard provide comfortable typing experience.Two-stage Adjustable Tilt Legs:Anti-slip and two-stage adjustable tilt outriggers,available in two different heights according to different needs.
Here is the command…
"123456" | Measure-Object -Character
Another way to run the command is to specify the string, “123456” with the InputObject variable instead of piping it…
Measure-Object -InputObject "123456" -Character
Both commands produce the same result, 6!

Example 2: Count a Specific Character in a String
Now, for a more advanced example – what if you want to count the number of a specific character in a string?
For example, let’s say you want to count the number of times that the number “2” occurs in this string:
123456225
The first step is to convert the string into a Unicode character array. To achieve this, use the ToCharArray Method.
Here is the command…
"123456225".ToCharArray()
What the command does is break down the string into members of a PowerShell Array. Here is the result…

Now that you have converted the string into an array, the next step is to pipe it to Where-Object. Then, in the Where-Object filter block, use the $_ automatic variable to return the characters you want to count.
In this example, we want to count all the occurrences of “2”. This is the command that does this job…
"123456225".ToCharArray() | Where-Object {$_ -eq '2'}
The command returns only the characters we want to count.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.

Finally, pipe the last command to Measure-Object.
"123456225".ToCharArray() | Where-Object {$_ -eq '2'} | Measure-Object
The final result tells us that the character, “2” appeared 3 times in the original string, “123456225”.

As you can see from the last command, the result has a bunch of other information. It also includes the word “Count”.
What if you want to display the number of characters without these other irrelevant information?
Simply enclose the pervious command in a () bracket, followed by a period (.). Finally, add the word Count.
Count is the property highlighted in the last screenshot. It is the same PowerShell Count Property we have been discussing in this guide.
("123456225".ToCharArray() | Where-Object {$_ -eq '2'} | Measure-Object).Count
Here you go, easy-peasy!

Example 3: Count the Number of Lines in a Text File
The examples in this section are getting exciting!
In this sub-section, I want to up the game a bit. I want to show you how to count the number of lines in a text file.
Let’s say you want to count the number of lines in the text file shown in this screenshot…

The first step is to use the Get-Content command to return the content of the file. Then pipe the output to Measure-Object and specify the Line parameter.
Best Value
- 【Dreamy Rainbow Gaming Keyboard】K521 Gaming Keyboard Adopts a Different LED Backlight Design, Upgraded on the Traditional LED Backlight Effect, Making the Light More Penetrating, Giving You a More Dazzling Visual Effect, Making Your Gaming Process More Enjoyable
- 【One Touch Opens & Visual Feast】The K521 Red Dragon Keyboard has a One-Touch on/off Lighting Button for Added Convenience. It also has a Three-Position Adjustable Breathing Mode and a Four-Position Adjustable Brightness Lighting Mode
- 【Mechanical Feeling & Fast Tapping】The PC Keyboard Keys are Designed for Mechanical Feeling, Giving You a Better Feel During Use and the Ability to Trigger Keys Quickly, Allowing You to Win All Your Games
- 【19 Keys Anti-Ghosting Keyboard】Anti-Ghosting Ensures Every Button Can Be Triggered. This Allows You to Trigger Key Combinations In The Game Accurately, And Each Skill Can Be Accurately Released to Increase Your Winning Rate. Redragon K521 Will Be Your Perfect Partner
- 【12 Multimedia Combination Keys】The K521 Wired Gaming Keyboard is Equipped with 12 Multimedia Keys That Can Greatly Enhance Your Gaming/Office Efficiency and Make It More Convenient to Use
Here is the final command…
Get-Content -Path D:\PS-Tutorial\file-with-numbers.txt | Measure-Object -Line
And here is the result…6 lines in the text file…

Alternatively, if you want to count the number of words in the text file, replace the Line parameter with Word.
Get-Content -Path D:\PS-Tutorial\file-with-numbers.txt | Measure-Object -Word
Coincidentally, there are also 6 words.

Example 4: Count Lines in a CSV File
In this next example, I want to count the number of lines in this CSV file. As you can see, there are 15 lines.

The approach is similar to counting the number of lines in a text file. However, it is less complicated.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →To count the number of lines in the CSV file above, firstly, use the Import-Csv command to list the content of the CSV file. Then, pipe the output of the Import-Csv command to Measure-Object.
Here is the final command…
Import-Csv D:\PS-Tutorial\20240313_140229.csv | Measure-Object
And the result…

Once again, if you want to display just the number of lines, run the command below…
(Import-Csv D:\PS-Tutorial\13-03-2024.csv | Measure-Object).Count

Example 5: Count Occurrences of String in a File
This is yet another exciting PowerShell Count example! In this section, I want to count the number of occurrences of the word “Bytes” in the text file in this screenshot…

As I already showed in a previous example, the first step is to use the Get-Content command to list the content of the text file.
Get-Content -Path D:\PS-Tutorial\folder-names.txt
Then, pipe the result to Where-Object and filter by the name of the words I want to count…
Get-Content -Path D:\PS-Tutorial\folder-names.txt | Where-Object {$_ -eq 'Bytes'}
Finally, pipe the result of the last command to Measure-Object.
Get-Content -Path D:\PS-Tutorial\folder-names.txt | Where-Object {$_ -eq 'Bytes'} | Measure-Object
To display just the result, modify the command as shown below..
(Get-Content -Path D:\PS-Tutorial\word_Occurrences.txt | Where-Object {$_ -eq 'Bytes'} | Measure-Object).Count
The result is 4.

Conclusion
Counting objects in PowerShell is a must-have skill for scripting. Fortunately, you can do this easily using the Count method or the Measure-Object cmdlet.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchHope we met your expectations with this guide. If we did, respond Yes to the “Was this page helpful?” question below.
You could also leave comments using the “Leave a Reply” form at the bottom of this page.
Finally, for more PowerShell tech Itechguides, visit our Windows PowerShell How-To guide page. You may also find our Work from Home page very helpful.


The FT was the problem. It includes the column headings and this is counted as part of the resultset.
Hi Victor
I found the explanation here : https://www.reddit.com/r/PowerShell/comments/kakszd/count_and_measure_off_by_4/
Thanks for your time
Glad you found a fix. Would you mind posting the details of the fix here so other readers can benefit?