Counting lines of source code with PowerShell

How do you count the lines of code your application has? As far as I know Visual Studio does not provide this functionality, so needless to say, we are doing that with PowerShell πŸ˜‰

$num = 0
dir c:\root\ -include *.cs -Recurse | ForEach-Object { 
	$file=[array](Get-Content $_ ) 
	$num += $file.length 

You obviously need to change c:\root to your root folder path, and change the *.cs mask to the one applicable to your source code.

Tags: , ,


7 Responses to “Counting lines of source code with PowerShell”

  1. 1 Keith Hill October 31, 2007 at 10:37 pm

    Another approach would be:

    dir c:\root\ -include *.cs -Recurse | Get-Content | Measure -Line

  2. 2 Keith Hill October 31, 2007 at 10:37 pm

    Make that Measure-Object (measure is an alias I set up).

  3. 3 Joel "Jaykul" Bennett November 1, 2007 at 2:51 am

    By the way, “-filter *.cs” is a lot faster than “-include *.cs” … personally I like to not count empty lines, so I filter them out with something like:

    ls -recurse -filter *.cs | gc | ? { -not $_.Trim().Length -eq 0)) } | measure-object -line

    If you don’t want to count the comment lines, you could also filter those out (note that you have to change your comment string if you’re not working on C#, and that this doesn’t exclude /* comment blocks */)

    ls -recurse -filter *.cs | gc | ? { $str = $_.Trim(); -not ($str.StartsWith(“//”) -or ($str.Length -eq 0)) } | measure -line

  4. 4 xaegr November 1, 2007 at 3:20 am

    Joel, measure-object -line will skip empty lines by default. But for other commands you can filter empty lines just this way: |?{$_}

  5. 5 dmitrysotnikov November 1, 2007 at 9:53 am

    Wow, I didn’t know about Measure-Object – it turns the script into a real one-liner – which is always the goal here, right? πŸ˜‰

    Learning something new every day! Thanks guys!

  6. 6 Artem November 1, 2007 at 10:15 am

    It was first script in Monad shell I’ve witten myself. Thank you for reminding πŸ™‚

  7. 7 fersis November 5, 2007 at 3:57 pm

    thats very useful , i will use it

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

My Recent Tweets


The posts on this blog are provided β€œas is” with no warranties and confer no rights. The opinions expressed on this site are mine and mine alone, and do not necessarily represent those of my employer - WSO2 or anyone else for that matter. All trademarks acknowledged.

Β© 2007-2014 Dmitry Sotnikov

October 2007
« Sep   Nov »

%d bloggers like this: