Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@appakz
Created January 25, 2012 03:13
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save appakz/1674457 to your computer and use it in GitHub Desktop.
Save appakz/1674457 to your computer and use it in GitHub Desktop.
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
Copy link

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

@petwolfe
Copy link

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

@grepit
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
Copy link

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