PowerShell: How to Count Number of Lines in File


You can use the following methods in PowerShell to count the total number of lines in a file:

Method 1: Count Number of Lines in File

(Get-Content "c:\users\bobbi\nba_data.csv").Length

This particular example counts the number of lines in the file named nba_data.csv.

By default, this method also counts lines that are blank in the file.

Method 2: Count Number of Non-Empty Lines in File

(Get-Content "c:\users\bobbi\nba_data.csv" | Select-string .).Length

This particular example counts only the number of non-empty lines in the file named nba_data.csv.

The following examples show how to use both methods in practice.

Example 1: Count Number of Lines in File Using PowerShell

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

  • c:\users\bobbi\nba_data.csv

We can use the following syntax to view the contents of this file:

Get-Content "c:\users\bobbi\nba_data.csv"

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

We can use the following syntax to count the total number of lines in the file:

(Get-Content "c:\users\bobbi\nba_data.csv").Length

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

PowerShell count number of lines in file

We can see that there are 11 total lines in the file.

Example 2: Count Number of Non-Empty Lines in File Using PowerShell

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

  • c:\users\bobbi\nba_data.csv

We can use the following syntax to view the contents of this file:

Get-Content "c:\users\bobbi\nba_data.csv"

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

There are 13 total lines but 2 of the lines are blank.

To count only the non-empty lines in the file, we can use the following syntax:

(Get-Content "c:\users\bobbi\nba_data.csv" | Select-string .).Length

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

PowerShell count non-empty lines in file

We can see that there are 11 total non-empty lines in the file.

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