How to Count Words in a File Using PowerShell?

Do you need to count the number of words in a file? Check out this tutorial. In this practical tutorial, I explain how to count words in a file using PowerShell. We will explore various methods with examples.

To count words in a file using PowerShell, you can utilize the Measure-Object cmdlet. First, retrieve the file content with Get-Content, then pipe it to Measure-Object with the -Word parameter. For example, the command Get-Content “C:\MyFolder\file.txt” | Measure-Object -Word will return the word count in the specified file.

Count Words in a File Using PowerShell

PowerShell provides different methods to count words in a file. Let us check each method with examples.

Method 1: Using Measure-Object

There is another super easy method available in PowerShell. You can use the Measure-Object cmdlet to count words in a file in PowerShell.

Here is an example.

# Define the path to the file
$filePath = "C:\MyFolder\example.txt"

# Read the content of the file and count the words
$wordCount = Get-Content $filePath | Measure-Object -Word

# Display the word count
$wordCount.Words

In this script, Get-Content reads the content of the file located at the specified path, and Measure-Object -Word counts the words. The result is stored in the $wordCount variable, which is then displayed.

Here is the output in the screenshot below after I executed the above PowerShell script using the VS code editor.

Method 4: Using Measure-Object There is another super easy method available in PowerShell. You can use the Measure-Object cmdlet to count words in a file in PowerShell. Here is an example. # Define the path to the file $filePath = "C:\MyFolder\example.txt" # Read the content of the file and count the words $wordCount = Get-Content $filePath | Measure-Object -Word # Display the word count $wordCount.Words In this script, Get-Content reads the content of the file located at the specified path, and Measure-Object -Word counts the words. The result is stored in the $wordCount variable, which is then displayed.

Check out PowerShell Copy-Item

Method 2: Count Words Using Get-Content and String Methods

The easiest way to count words in a file using PowerShell is to read the file content and then split the content into words. Here’s how you can do it:

  1. Read the file content: Use the Get-Content cmdlet to read the content of the file.
  2. Split the content into words: Use the -split operator to split the content based on whitespace.
  3. Count the words: Use the .Length property to get the number of words.

Here is a complete PowerShell script that will count the number of words presented in a file.

# Path to the text file
$filePath = "C:\MyFolder\example.txt"

# Read the content of the file
$content = Get-Content -Path $filePath -Raw

# Split the content into words
$words = $content -split '\s+'

# Count the number of words
$wordCount = $words.Length

# Output the word count
Write-Output "The file contains $wordCount words."

You can see here that I executed the above PowerShell script using VS code, and it gave me the output like the screenshot below. It showed me the exact count.

powershell count words in file

Method 3: Using Regular Expressions

Another method you can use to count the words in a file in PowerShell is to use regular expressions to match words in the file content. This is how to do it:

  1. Read the file content: Use Get-Content with the -Raw parameter.
  2. Match words using regex: Use [regex]::Matches() to find all word matches.
  3. Count the matches: Use the .Count property to get the number of words.

Here’s the complete PowerShell script method.

# Path to the text file
$filePath = "C:\MyFolder\example.txt"

# Read the content of the file
$content = Get-Content -Path $filePath -Raw

# Define the regex pattern for matching words
$pattern = '\b\w+\b'

# Find all matches
$matches = [regex]::Matches($content, $pattern)

# Count the number of matches
$wordCount = $matches.Count

# Output the word count
Write-Output "The file contains $wordCount words."

I executed the entire script using Visual Studio code, and you can see the output in the below screenshot.

Count Words in a File Using PowerShell

Method 4: Using a Custom Function

You can create a custom function and reuse it everywhere. This function can count words in any file by simply passing the file path as an argument.

Here’s how you can create and use such a function:

function Get-WordCount {
    param (
        [string]$filePath
    )

    # Read the content of the file
    $content = Get-Content -Path $filePath -Raw

    # Split the content into words
    $words = $content -split '\s+'

    # Return the word count
    return $words.Length
}

# Example usage
$filePath = "C:\MyFolder\Example.txt"
$wordCount = Get-WordCount -filePath $filePath

# Output the word count
Write-Output "The file contains $wordCount words."

The above method you can reuse everywhere.

Count Words, Lines, and Characters in a file using PowerShell

There will be times when you might want to count not just words but also lines and characters. Below is a complete script to count words, lines, and characters in a file using PowerShell.

# Define the path to the file
$filePath = "C:\MyFolder\example.txt"

# Read the content of the file and count words, lines, and characters
$stats = Get-Content $filePath | Measure-Object -Word -Line -Character

# Display the counts
"Words: $($stats.Words)"
"Lines: $($stats.Lines)"
"Characters: $($stats.Characters)"

This script extends the capabilities of the previous one by adding -Line and -Character parameters to Measure-Object, allowing you to get a count of lines, characters, and words.

Below is the screenshot of the output it gave after I executed the script using the VS code editor.

Count Words Lines and Characters in a file using PowerShell

Count Words in Multiple Files using PowerShell

Sometimes, you may need to count words in multiple files, and it is also very easy to do in PowerShell.

Here is a complete script that will count words in all text files in a folder using PowerShell.

# Define the path to the directory containing the files
$directoryPath = "C:\MyFolder"

# Get all text files in the directory
$files = Get-ChildItem $directoryPath -Filter *.txt

# Loop through each file and count the words
foreach ($file in $files) {
    $content = Get-Content $file.FullName
    $wordCount = ($content | Measure-Object -Word).Words
    "$($file.Name) has $wordCount words"
}

This script lists all .txt files in a given directory and counts the words in each file. Finally, it will show the file name along with its word count as the output.

Count specific words in a file using PowerShell

Sometimes, you might get a requirement to count a specific word in a file.

To count specific words within a file using PowerShell, you can utilize the Select-String cmdlet. This cmdlet is similar to the grep command in Unix/Linux, and can be used to search for text patterns in input strings and files using regular expression matching.

Here’s a step-by-step explanation of how you can count occurrences of a specific word within a file:

  1. The Select-String cmdlet allows you to search through text and files to find specific patterns. When you want to count occurrences of a specific word, you would use this cmdlet and specify the pattern (the word) you are looking for.
  2. You would typically use Get-Content to read the file’s content before piping it into Select-String, or you can directly use Select-String on the file.
  3. After Select-String has found the matches, you can count them by accessing the Matches property or simply piping the results to the Measure-Object cmdlet.

Here’s a simple PowerShell script that counts the number of times the word “PowerShell” appears in a file called “example.txt”:

# Define the path to the file and the specific word
$filePath = "C:\MyFolder\example.txt"
$wordToCount = "PowerShell"

# Count the occurrences of the word
$wordCount = (Select-String -Path $filePath -Pattern "\b$wordToCount\b" -AllMatches).Matches.Count

# Display the count
"Number of times the word '$wordToCount' appears: $wordCount"

In this script:

  • "\b$wordToCount\b" is a regular expression that matches the word “PowerShell” as a whole word (\b denotes a word boundary).
  • -AllMatches tells Select-String to find every match in the file.
  • .Matches.Count retrieves the count of all the matches found.

This approach ensures that you are counting only whole word matches rather than partial matches (e.g., “PowerShell” will be counted, but “PowerShellScript” will not).

You can clearly see the output in the screenshot below after I executed the script.

Count specific words in a file using PowerShell

Count unique words in a file using PowerShell

There will be times when you need to retrieve unique words from a file, and PowerShell is the best option for this.

Counting unique words in a file using PowerShell can be achieved by combining several cmdlets. It includes reading the file’s content, splitting the text into individual words, and then using a combination of Group-Object and Sort-Object cmdlets to filter out unique words and count them.

Here’s a step-by-step explanation followed by a complete script:

  • Read the File: Use Get-Content to read the contents of the file.
  • Split the Content into Words: Split the content into individual words. This can be done by replacing non-word characters with a space and then using the -split operator.
  • Group and Sort the Words: Use Group-Object to group identical words together and Sort-Object to sort them, if needed.
  • Count the Unique Words: The number of unique groups corresponds to the number of unique words.

Here’s a PowerShell script that reads a file and counts the number of unique words it contains:

# Define the path to the file
$filePath = "C:\MyFolder\example.txt"

# Read the file and split the content into words
$words = Get-Content -Path $filePath -Raw | ForEach-Object { ($_ -replace '[^\w\s]', ' ') -split '\s+' }

# Group the words, select unique ones, and count them
$uniqueWords = $words | Group-Object | Measure-Object

# Display the count of unique words
"Number of unique words: $($uniqueWords.Count)"

In this script:

  • Get-Content -Path $filePath -Raw reads the entire file content as a single string.
  • -replace '[^\w\s]', ' ' replaces any non-word and non-space characters with a space.
  • -split '\s+' splits the string by one or more whitespace characters into an array of words.
  • Group-Object groups the words, effectively filtering out duplicates.
  • Measure-Object counts the number of unique groups.

After I executed the above script using VS code, it gave me the unique word count of the specified file, you can see in the screenshot below:

Count unique words in a file using PowerShell

Conclusion

I hope now you have an idea of how to count the number of words in a file using PowerShell. I have also explained:

  • Count Words, Lines, and Characters in a file using PowerShell
  • How to Count Words in Multiple Files using PowerShell
  • Count specific words in a file using PowerShell
  • How to Count unique words in a file using PowerShell

You may also like the following tutorials:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.