Home » PowerShell Tips » PowerShell Count Lines in File and Words

PowerShell Count Lines in File and Words

In this quick article, I will explain how to count lines in a file and get a number of lines and words in the file in a specified directory using a PowerShell script.

PowerShell Get-Content cmdlet gets the content of the file specified by the path parameter and uses the Measure-Object cmdlet in the PowerShell count lines file and words in the file.

Let’s understand using Get-Content and Measure-Object cmdlet to print the number of lines in a file, word count and character count in a file.

Note: Check if the file exists in PowerShell before you use the above script to get the file name!

PowerShell Count Lines in File

Let’s consider an example of reading the content of a file specified at location D:\PowerShell\ and count lines in a file and words in the file as below.

 Get-Content -Path D:\PowerShell\ZeroMileFile.txt | Measure-Object -Line -Word -Character

In the first command, the PowerShell Get-Content cmdlet reads the content of the file specified by the -Path parameter and passes the output to the second command.

Get-Content - Get file content
Get-Content – Get file content

The second command uses the PowerShell Measure-Object cmdlet to count the number of lines in a file in a specified directory.

Measure-Object cmdlet has Line, Word, and Character parameters to get the number of lines, total words, and total characters in a file.

The output of the above PowerShell script counts the total number of lines in a file, the total words in a file, and count total Characters in the file.

PowerShell Count Line in File
PowerShell Count Line in File

Cool Tip: How to get file name without extension in PowerShell!

Conclusion

In the above article, we learned to use PowerShell to count lines in a file in a specified directory. The Get-Content cmdlet gets the content of the file and uses the Measure-Object cmdlet to get the total number of lines in the file.

Read here about how to create a multiline string in PowerShell!

You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.

Leave a Comment