Count word occurrences in a text file with a single PowerShell pipeline:
(Get-Content .\words.txt) -Split '\W+' | Group-Object | Sort-Object -Descending Count | Select-Object Count, Name
Example output:
Count Name
----- ----
12 the
9 a
7 to
5 PowerShell
3 file
How It Works
Get-Content .\words.txt
Reads the file as an array of lines.
-Split '\W+'
Splits each line on one or more non-word characters (\W+ matches spaces, punctuation, newlines, etc.), producing an array of individual words.
Group-Object
Groups identical words together. Each group has a Count and a Name (the word itself). Matching is case-insensitive by default.
Sort-Object -Descending Count
Sorts groups from highest count to lowest.
Select-Object Count, Name
Outputs just the count and word columns, in that order.
Case-Sensitive Counting
By default Group-Object treats The and the as the same word. To distinguish them:
(Get-Content .\words.txt) -Split '\W+' | Group-Object -CaseSensitive | Sort-Object -Descending Count | Select-Object Count, Name
Skip Blank Entries
Splitting on whitespace can produce empty strings at line boundaries. Filter them out with Where-Object:
(Get-Content .\words.txt) -Split '\W+' | Where-Object { $_ } | Group-Object | Sort-Object -Descending Count | Select-Object Count, Name
Where-Object { $_ } drops any empty or whitespace-only string.
Top N Words
Pipe to Select-Object with -First to limit results:
(Get-Content .\words.txt) -Split '\W+' | Where-Object { $_ } | Group-Object | Sort-Object -Descending Count | Select-Object -First 10 Count, Name
Count Words from Any String
The same pipeline works on any string — not just files. Pipe from the clipboard, a variable, or command output:
# From a variable
$text = "to be or not to be that is the question"
$text -Split '\W+' | Group-Object | Sort-Object -Descending Count | Select-Object Count, Name
Output:
Count Name
----- ----
2 to
2 be
1 or
1 not
1 that
1 is
1 the
1 question