PowerShell Script: Count Rows in CSV Files

Are you dealing with CSV files and in need of a quick row count using PowerShell? Look no further! In this post, we’ll guide you through a script that effortlessly counts rows within multiple CSV files.

Count Rows in Multiple CSV Files with PowerShell

To get started, open PowerShell ISE for a convenient platform to run our PowerShell script. Copy and paste the script below into the PowerShell ISE window, making sure to adjust the directory path to your folder containing CSV files. Save and run the script.

# Count rows in CSV files PowerShell
#  > set directory to folder containing csv files
Get-ChildItem "C:\myfolder\" -Recurse -Filter "*.csv" |
Foreach-Object { 
    $fileStats = Get-Content $_.FullName | Measure-Object -line
    $linesInFile = $fileStats.Lines -1
    Write-Host "$_,$linesInFile" 
}
Count Rows in CSV Files PowerShell

This script provides an output that you can easily transfer into Excel, helping you keep track of row counts in your CSV files.

Verify Data and Check for Issues

The script output above helps us identify potential data issues within the CSV files. For instance, if you spot a row count of -1, it indicates that the file is empty. This quick check allows you to disregard files with no data, streamlining your data validation process.

PowerShell Row Count Output

Another common issue as a SQL Server DBA is when : CSV files with the phrase “(12345 rows affected)” at the end. This issue often arises when exporting SQL Server query results to CSV. The reason for this is that we need to include SET NOCOUNT within the SQL query when using Results to Text.

Hope this helps!

One thought on “PowerShell Script: Count Rows in CSV Files

Leave a Reply

Your email address will not be published. Required fields are marked *