In this quick article, I will explain how to count lines in file and get number of lines and words in the file in specified directory using PowerShell script.
Get-Content cmdlet get the content of file specified by path parameter and using Measure-Object cmdlet in PowerShell count lines file and words in file.
Let’s understand using
Measure-Object cmdlet to print number of lines in file.
Note: Check if file exists in PowerShell before you use above script to get file name!
PowerShell Count Lines in File
Let’s consider an example to read the content of file specified at location D:\PowerShell\ and count lines in file and word in file as below
Get-Content -Path D:\PowerShell\ZeroMileFile.txt | Measure-Object -Line -Word -Character
In the first command, PowerShell Get-Content cmdlet read the content of file specified by -Path parameter and pass output to second command as below
Second command uses PowerShell Measure-Object cmdlet to count number of lines in file in specified directory.
Measure-Object cmdlet has Line, Word and Characters parameters to get number of lines, total words and total characters in file as below
As in the above image, measure-object cmdlet returns total number of lines in file, total words and Characters in file.
Cool Tip: How to get file name without extension in PowerShell!
In above article, we learned using PowerShell to count lines in file in specified directory.
Get-Content cmdlet get the content of file and using
Measure-Object cmdlet to get total number of lines in the file.
Read here about how to create multiline string in PowerShell!
You can find more topics about PowerShell Active Directory commands and PowerShell basics on ShellGeek home page.