How to Count Objects in PowerShell

Photo of author

By Victor Ashiedu

Published

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.

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.

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.

$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.

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.

(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.

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:

Get-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.

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.

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.

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.

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.

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.

Hope 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.

About the Author

Photo of author

Victor Ashiedu

Victor is the founder of InfoPress Media, publishers of Ilifeguides and Itechguides. With 20+ years of experience in IT infrastructure, his expertise spans Windows, Linux, and DevOps. Explore his contributions on Itechguides.com for insightful how-to guides and product reviews.

Related Articles

Get in Touch

We're committed to writing accurate content that informs and educates. To learn more, read our Content Writing Policy, Content Review Policy, Anti-plagiarism Policy, and About Us.

However, if this content does not meet your expectations, kindly reach out to us through one of the following means:

  1. Respond to "Was this page helpful?" above
  2. Leave a comment with the "Leave a Comment" form below
  3. Email us at [email protected] or via the Contact Us page.

12 thoughts on “How to Count Objects in PowerShell”

  1. Hi Victor
    Thanks for your reply.
    You missed the important part : Sort-Object
    Let’s say I want to retrieve all processes named “svchost” and sort them by largest WS usage, I do :

    [array]$process = Get-Process -Name svchost `
    | Select-Object -Property @{Name=”Process Name”;Expression={$_.ProcessName}}, `
    @{Name=”Process ID”;Expression={$_.Id}}, PM, WS, NPM, Handles `
    | Sort-Object {$_.WS} `
    | FT -AutoSize

    $process
    $process.count

    Already it does not know how to count, it displays 12 lines but says the count is 16… anyways.

    What I really want is to get only the first 5 from this list (5 top consumers), so I add “Select-Object -Last 5”

    [array]$process = Get-Process -Name svchost `
    | Select-Object -Property @{Name=”Process Name”;Expression={$_.ProcessName}}, `
    @{Name=”Process ID”;Expression={$_.Id}}, PM, WS, NPM, Handles `
    | Sort-Object {$_.WS} `
    | Select-Object -Last 5 `
    | FT -AutoSize

    $process
    $process.count

    It lists 5 as I asked for, but says it listed 9.

    In this example, when executed on my machine, there are 4 more in the count, than what is in the array, for both cases.

    Thanks for your help

    Reply
  2. I create an arry from a larger list of items, using Select-Object -Last 10. The .count property of my array is always 10, whether it is empty, countains 3 o4 4 items, or 10. Always. Is this a bug or is there a way around that ?

    [array]$ToReturnToVault = Get-VBRTapeMedium -Library $Media_Pool.LibraryId `
    | Where-Object {$_.Location -like “Slot” -and -not $_.IsFree} `
    | Select-Object -Property @{N=”SlotNo”;E={$_.Location.SlotAddress +1}}, `
    @{N=”Barcode”;E={$_.Barcode}},Free,IsExpired,MediaSet,Location,ExpirationDate,IsFree,LastWriteTime `
    | Sort-Object {$_.LastWriteTime} `
    | Select-Object -Last 10 `
    | FT -AutoSize

    $ToReturnToVault

    SlotNo Barcode Free IsExpired MediaSet Location ExpirationDate IsFree LastWriteTime
    —— ——- —- ——— ——– ——– ————– —— ————-
    5 037V01L4 119794565120 False Tuesday Daily media set 2021-06-08 Slot 06/08/2021 6:13:30 AM False 11/06/2021 7:36:24 AM
    1 037V02L4 443220492288 False Tuesday Daily media set 2021-06-08 Slot 06/08/2021 11:11:45 AM False 11/06/2021 2:35:59 PM
    18 030V02L4 535094624256 False Saturday Weekly media set 2021-06-12 Slot 07/08/2021 3:49:41 AM False 12/06/2021 6:03:44 AM
    22 030V01L4 42750443520 False Saturday Weekly media set 2021-06-12 Slot 07/08/2021 6:03:44 AM False 12/06/2021 6:22:46 AM
    3 047V01L4 830638915584 False Sunday Daily media set 2021-06-13 Slot 11/08/2021 2:06:18 AM False 16/06/2021 2:06:27 AM
    20 047V02L4 832132087808 False Sunday Daily media set 2021-06-13 Slot 11/08/2021 2:06:27 AM False 16/06/2021 2:06:49 AM

    $ToReturnToVault.count
    10

    Reply
    • Hi Syltrem,

      Thank you for posting your question. To replicate the question, I developed a similar code but I used the Get-Process command because I do not have the modules you used in your example.

      Here is my replica script:

      [array]$process = Get-Process -Name chrome | Where-Object {$_.CPU -ge “500”}
      Select-Object -Property @{Name=”Process Name”;Expression={$_.ProcessName}}, `
      @{Name=”Process ID”;Expression={$_.Id}}, PM, WS, NPM, Handles -Last 2
      $process.count

      Like your script, the $process.count will always return values less than or equal to the value specified in the “Last” parameter of Select-Object.

      I am not sure what you are trying to achieve with the number specified in the “Last” parameter of Select-Object. If you let me know what that number, 10 represents and what you want to achieve, it may be better to specify it somewhere else in the script.

      For example, we may be able to specify it in the Where-Object block.

      Reply
  3. If i wants to extract a particular event id count means how shall i modify the below code. (Get-EventLog -LogName System | Where-Object {$_.EntryType -eq “Warning”} anyone can help me please?

    Reply
    • Do you know the event ID you want to extract? You can modify the Where-Object bit of the command to look like this:

      Get-EventLog -LogName System | Where-Object {$_.EntryType -eq “Warning” -and $_.EventID -eq 6000}

      The modified command displays all warning events with ID 6000

      Reply
  4. .count doesn´t exists on a System.Object, you need to use Measure.
    I don´t really understand the difference, maybe can explain that more also?

    Reply

Leave a comment

Send this to a friend