Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Quick and dirty powershell script for counting lines in each file of a folder
#Quick and dirty PS script for counting lines of code in a directory. Output is dumped to a simple CSV file.
#Note that this script doesn't count blank lines.
#Parameters:
# path - the path containing the code files (note that the script will recurse through subfolders
# outputFile - fully qualified path of the file to dump the CSV output
# include (Optional) - file mask(s) to include in the count (deafults to *.*)
# exclude (Optional) - file mask(s) to exclude in the count (defaults to none)
# Example (count lines in target path including *.cs but excluding *.designer.cs)
# .\countLOC.ps1 -path "C:\code\MyProject" -outputFile "C:\code\loc.csv" -include "*.cs" -exclude "*.designer.cs"
param([string]$path, [string]$outputFile, [string]$include = "*.*", [string]$exclude = "")
Clear-Host
Get-ChildItem -re -in $include -ex $exclude $path |
Foreach-Object { Write-Host "Counting $_.FullName"
$fileStats = Get-Content $_.FullName | Measure-Object -line
$linesInFile = $fileStats.Lines
"$_,$linesInFile" } | Out-File $outputFile -encoding "UTF8"
Write-Host "Complete"
@donzacharias

This comment has been minimized.

Copy link

donzacharias commented Oct 8, 2013

Thanks, this was just the thing I needed today! Worked great to count lines of logfiles. Gotta love PS...

@petwolfe

This comment has been minimized.

Copy link

petwolfe commented Dec 21, 2015

Is there anyway to do this for data files which are zipped? (Unzip, count lines and zip it back)

@grepit

This comment has been minimized.

Copy link

grepit commented Aug 18, 2016

You can also use this one liner (feel free to add -Recurse to include sub dirs or use -ex to exlcued a pattern). Note: this will give you total not by each file.
(Get-ChildItem -File | Get-Content | Measure-Object -line).Lines

@muhammedshihabvk

This comment has been minimized.

Copy link

muhammedshihabvk commented Jul 19, 2020

Number of lines
Get-Content -path .\hostList.txt | Measure-Object -Line | select-object -ExpandProperty lines

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.