As PowerShell enthusiasts, we often find ourselves immersed in tasks that involve processing and analyzing data. Whether it’s counting rows in a CSV file or tracking the progress of specific operations, having a reliable counting mechanism is crucial.
In this blog post, we’ll explore how the Measure-Object PowerShell cmdlet can be a powerful ally in counting rows, words, and lines in various scenarios. Additionally, we’ll dive into its applications for counting files and dive into the intricacies of row counting in CSV files,
PowerShell: Count Files in a Directory
One common scenario in PowerShell scripting involves counting files in a directory. While manual counting can be tedious, Measure-Object makes this task a breeze. The following command will effortlessly count the files in your current working directory:
# Count files in current directory (Get-ChildItem -Recurse -Force).Count # Count files in specific directory (Get-ChildItem -Path 'd:\demoFiles' -Recurse -Force).Count
PowerShell: Counting Lines, Words & Characters
Measure-Object extends its prowess beyond file counting, proving invaluable in text file analysis. Let’s explore its capabilities in counting lines, words, and characters within text or other types of files.
Count Lines in a Text File
# Count lines in a text file (Get-Content .\DemoFile_1.txt | Measure-Object -Line).Lines
Count Words in a Text File
# Count words in a text file (Get-Content .\DemoFile_2.txt | Measure-Object -Word).Words
Count Characters in a Text File
# Count characters in a text file (Get-Content .\DemoFile_3.txt | Measure-Object -Character).Characters
PowerShell: Measuring Object Properties
This script below utilizes the Get-ChildItem cmdlet to recursively fetch all CSV files in the designated folder, and subsequently employs Measure-Object to calculate the number of lines in each file.
To obtain accurate row counts, the script subtracts one from the total lines, as CSV files commonly include a header row. The Write-Host cmdlet then displays the filename alongside its corresponding row count.
Set the directory to your folder containing CSV files before running.
# Count rows in CSV files PowerShell # Set the directory to your folder containing csv files before running Get-ChildItem "C:\myfolder\" -Recurse -Filter "*.csv" | Foreach-Object { $fileStats = Get-Content $_.FullName | Measure-Object -line $linesInFile = $fileStats.Lines -1 Write-Host "$_,$linesInFile" }
For more information and a guide on how to count rows in CSV files using PowerShell, feel free to check out our dedicated post on this:
One thought on “PowerShell: Counting Files, Words and Rows”