PowerShell: Count Number of Lines in Multiple Files


You can use the following syntax to count the total number of lines in multiple files using PowerShell:

(Get-ChildItem -path $my_folder -Recurse -File | Get-Content | Measure-Object -line).Lines

This particular example will count the total number of lines across all files in the folder specified at the path in $my_folder.

The following example shows how to use this syntax in practice.

Example: How to Count Number of Lines in Multiple Files Using PowerShell

Suppose that we have a folder located at the following path:

  • c:\users\bobbi\data1

We can use the following syntax to view all of the files in this folder:

$my_folder = "c:\users\bobbi\data1"
Dir $my_folder

The following screenshot shows how to use this syntax in practice:

We can see that there are three text files in this folder.

To count the number of lines in one of these files, such as teams.txt, we could use the following syntax:

(Get-Content "c:\users\bobbi\data1\teams.txt").Length

We can use similar syntax to get the total line count in each file:

From the output we can see:

  • teams.txt has 10 total lines
  • players.txt has 12 total lines
  • conferences.txt has 6 total lines

If we would like to get the total line count for all of the files in this folder, we can use the following syntax instead:

(Get-ChildItem -path $my_folder -Recurse -File | Get-Content | Measure-Object -line).Lines

The following screenshot shows how to use this syntax in practice:

PowerShell count total lines in multiple files

We can see that there are 28 total lines across all of the files in this folder.

We can confirm this is correct by adding the total number of lines in each individual file:

  • Total Lines: 10 + 12 + 6 = 28

This matches the number shown in the output.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to List Files in Directory by Date
PowerShell: How to List All Files in Directory to Text File
PowerShell: How to Delete All Files with Specific Extension

Leave a Reply