Refactored Codes
How to find number of lines, number of words and number of characters in powershell command line
In Linux operating system, we have wc command to give us the count of lines, words and chars in a file. Can we do that in Powershell? The answer is YES!!!. You can watch me running the commands on youtube. [embed]https://youtu.be/1MAG_STV7i8[/embed] Before we run the command, let us create a sample file to use it in our test. And, you can also verify the output provided in my blog, with the one generated when you run the commands. Depending on the version of powershell, the results can be different. I am running Powershell 7.4.5.
Get-Command | Out-File -FilePath commands.txt
This command will create a file commands.txt, which contains the output of Get-Command. Let us run our command one by one. To count lines, run the command.
Get-Content .\commands.txt | Measure-Object -Line
To count words, run the command.
Get-Content .\commands.txt | Measure-Object -Word
To count characters, run the command
Get-Content .\commands.txt | Measure-Object -Character
Here is the screenshot of the command executed and it's output. It contains the output of running measure-object. For, Cleaner output, You can use the Select-Object command to read only the desired Properties. Get-Content .\commands.txt | Measure-Object -Line | Select-Object -Property Lines Get-Content .\commands.txt | Measure-Object -Word | Select-Object -Property Words; Get-Content .\commands.txt | Measure-Object -Character | Select-Object -Property Characters;
PS D:\LearningPowerShell> Get-Content .\commands.txt | Measure-Object -Line | Select-Object -Property Lines

Lines
-----
 1773

PS D:\LearningPowerShell> Get-Content .\commands.txt | Measure-Object -Word | Select-Object -Property Words;

Words
-----
 7014

PS D:\LearningPowerShell> Get-Content .\commands.txt | Measure-Object -Character | Select-Object -Property Characters;

Characters
----------
    162857
Here is the screenshot of the Command execution and Output. This images shows that we can filter the output of Measure Object command using Select Objec to command