tags:

views:

480

answers:

4

I'm trying to find a way to count the total number of lines in all of the source files of a project I have. I've tried piping dir -r -name into measure-object -line, but that just counts the number of files I have.

Does anyone have a script to do this?

+5  A: 

dir *.txt -recurse | select Fullname,@{name="LineCount";expression={ @(get-content $.fullname).count }}

Shay Levy
This command isn't working for me. I get several "Select-Object : Cannot bind argument to parameter 'Path' because it is null." errors.
aphoria
I'm voting you up because I didn't know about the select command, and I'm kind of stoked about it. Still, though - you used `$__` instead of `$_`, you used `dir *.txt` instead of `dir -filter "*.txt"`, and your result still makes me add everything up when I'm done.
Dan Monego
Sorry for that Dan, the editor didn't show $_ so I doubled it, thanks for voting!
Shay Levy
+3  A: 
Get-ChildItem . -Include *.txt -Recurse | foreach {(Get-Content $_).Count}

Condensed down a bit with aliases:

GCI . -Include *.txt -Recurse | foreach{(GC $_).Count}

Will give results similar to this:

Lines Words               Characters              Property
----- -----               ----------              --------
   21
   40
   29
   15
  294
   13
   13
  107

EDIT: Modified to recurse through subfolders.

EDIT 2: Removed use of Measure-Object.

aphoria
+1  A: 

Thanks to everyone who answered. The way I ended up implementing this was

dir . -filter "*.cs" -Recurse -name | foreach{(GC $_).Count} | measure-object -sum
Dan Monego
It doesn't seem to work ...
dangph
dir . -filter "*.cs" -Recurse | foreach {(gc $_).Count} | measure-object -sum
dangph
Fixed to work. I should point out that yours doesn't seem to work either.
Dan Monego
D'oh. And I was being so careful too. Mine works if the '-filter' is changed to '-include'. I can't say I understand why filter doesn't work.
dangph
The problem with both mine and yours was fixed with the -name parameter to the first statement - only the filename and not the path were being passed to GC. I have no idea how I ended up posting that after creating a working version earlier.
Dan Monego
I was going to say, "copy-and-paste is your friend", but I would look like a fool if I said that now :)
dangph
+4  A: 
Get-ChildItem -Filter "*.cs" -Recurse | Get-Content | Measure-Object -line
Alex
Get-ChildItem *.cs -Recurse will recurse the directory, but (in powershell 1.0 at least) will only show the files ending with .cs in the current directory.
Dan Monego
Thanks!Yes, because in this case, *.cs matches 'path', rather than 'filter' parameter. To fix, you can write: Get-ChildItem . *.cs -Recurse …or Get-ChildItem -Filter "*.cs" -Recurse …
Alex