In Linux we have the "wc" command which allows us to count the number of characters, words and lines in a file.
But do we have a similar cmdlet in PowerShell. The Measure-Object cmdlet I tried could only count the number of lines but not the characters and words.
To count the total number of lines in the file in PowerShell, you first need to retrieve the content of the item using Get-Content cmdlet and need to use method Length() to retrieve the total number of lines.
Use Measure-Object to Get the String Length of a Variable in PowerShell. The Measure-Object cmdlet calculates the numeric properties of certain types of objects in the PowerShell. It counts the number of string objects' words, lines, and characters.
Word count (and more) using Measure-Object Linux has a command called wc that counts the number of lines and words in a file. Powershell has no such command but we can do something similar with the Measure-Object Cmdlet.
Get-Content [FILENAME] | Measure-Object -Character
It counts the number of characters in the file.
Get-Content [FILENAME] | Measure-Object -Word
It counts the number of words in the file.
Get-Content [FILENAME] | Measure-Object -Line
It counts the number of lines in the file.
Measure-Object do exactly that. You do have to specify the parameters you want measured for the characters, words and lines to be returned.
Example 3: Measure text in a text file
This command displays the number of characters, words, and lines in the Text.txt file. Without the Raw parameter, Get-Content outputs the file as an array of lines.
The first command uses Set-Content to add some default text to a file.
"One", "Two", "Three", "Four" | Set-Content -Path C:\Temp\tmp.txt Get-Content C:\Temp\tmp.txt | Measure-Object -Character -Line -Word Lines Words Characters Property ----- ----- ---------- -------- 4 4 15
Reference: Microsoft.Powershell.Utility/measure-object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With