Home » How to Count Lines in the File in PowerShell

How to Count Lines in the File in PowerShell

To count the total number of lines in a file, you can use the Get-Content cmdlet along with the Measure-Object cmdlet.

Method 1: Count lines in a file

Get-Content -Path $filePath | Measure-Object -Line

This example will return the total number of lines in a file.

The following example shows how to use this method to get the number of lines in a file in PowerShell.

Count Lines in a File in PowerShell

To count lines in a file in PowerShell, use the Get-Content cmdlet to read the content of the file and pipe the output to the Measure-Object cmdlet.

The following example shows how to use it with syntax.

Get-Content -Path C:\temp\myprocess.txt |Measure-Object -Line -Character -Word

In the above PowerShell script, the Get-Content reads the content of the file named “C:\temp\myprocess.txt” and pipes the output to the Measure-Object cmdlet. The Measure-Object cmdlet uses the -Line switch to get the number of lines in a file.

The output of the above PowerShell script is given below.

PS C:\> Get-Content -Path C:\temp\myprocess.txt |Measure-Object -Line

Lines Words Characters Property
----- ----- ---------- --------
  477

Conclusion

I hope the above article on how to count the number of lines in a file using PowerShell is helpful to you.

Using the Measure-Object cmdlet, you can count the number of lines, characters, and words in a file.

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