You can use the following methods in PowerShell to count the total number of rows in a CSV file:
Method 1: Count Number of Rows in CSV File (Suitable for Small Files)
(Get-Content 'nba_data.csv').Length
This particular example counts the number of rows in the file named nba_data.csv.
Note that this method works well for small files but will take a long time to run for larger files.
Method 2: Count Number of Rows in CSV File (Suitable for Large Files)
[int]$TotalLines = 0 $reader = New-Object IO.StreamReader 'nba_data.csv' while($reader.ReadLine() -ne $null){ $TotalLines++ } ($reader.Dispose())
This particular example also counts the number of rows in the CSV file named nba_data.csv but it will perform much faster on large files compared to the previous method.
This approach uses IO.StreamReader to load the file from disk and then uses the variable $TotalLines to hold the running count of lines in the file.
This approach is much more memory-efficient than using the Get-Content cmdlet and should be used when working with extremely large CSV files.
The following examples show how to use both methods in practice with the following file named nba_data.csv that contains information about various basketball players:

Example 1: Count Number of Rows in CSV File (Suitable for Small Files)
One way to count the total number of rows in this file is to use the Get-Content cmdlet with the length property to return the total line count:
(Get-Content 'nba_data.csv').Length
The following screenshot shows how to use this syntax in practice:

We can see that there are 11 total lines in the file.
Example 2: Count Number of Rows in CSV File (Suitable for Large Files)
Another way to count the total number of rows in the CSV file is to use the IO.StreamReader approach:
[int]$TotalLines = 0 $reader = New-Object IO.StreamReader 'nba_data.csv' while($reader.ReadLine() -ne $null){ $TotalLines++ } ($reader.Dispose())
The following screenshot shows how to use this syntax in practice:

When we print the $TotalLines counter variable we can see that it also returns a total row count of 11.
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
