Counting the number of occurrences of a string or file in PowerShell

I always forget how to do this, and Aleksandar Nikolić posted a really beautiful answer on

For a file:

-split (Get-Content .\test.txt | Out-String) | Where-Object { $_ -eq "test" } | Measure-Object | Select-Object -exp count

For a string:

$html.content -split "FeedbackItemSummaryModulePanel" | Measure-Object | Select-Object -Exp Count

Chrissy is a Cloud and Datacenter Management & Data Platform MVP who has worked in IT for over 20 years. She is the creator of the popular SQL PowerShell module dbatools, holds a master's degree in Systems Engineering and is coauthor of Learn dbatools in a Month of Lunches. Chrissy is certified in SQL Server, Linux, SharePoint and network security. You can follow her on Twitter at @cl.

Posted in PowerShell
3 comments on “Counting the number of occurrences of a string or file in PowerShell
  1. Curtis says:

    I am a ‘newby’ with Powershell… exactly how does your ‘For a string:’ code work?
    Is there something missing that I need to infer.

  2. Anvesh M Patel says:

    Nice Article !
    This is my pleasure to read your article.
    Really this will help to people of SQL Server Community.

    I have also prepared one article about, Script to count number occurrences of string in SQL Server.
    You can also visit my article, your comments and reviews are most welcome.

  3. Marc says:

    How can -split be used without an expression on the left. What’s it splitting??

Leave a Reply to Anvesh M Patel Cancel reply