Source lines of code count using PowerShell

Source lines of code (SLOC) is a software metric used to measure the size of a software program by counting the number of lines in the text of the program’s source code.

As we all know the disadvantages of this metric, sometimes we simply want to know.

Here’s a PowerShell script, that recursively searches for *.cs files and counts the lines (empty lines and comments are excluded)

(dir -include *.cs -recurse | select-string "^(\s*)//" -notMatch | select-string "^(\s*)$" -notMatch).Count

Brief description of what all parts are doing:

  • dir -include *.cs -recurse : Lists all *.cs files, you can add additional extensions using a comma.
  • select-string “^(\s*)//” -notMatch : Exclude comments.
  • select-string “^(\s*)$” -notMatch : Exclude empty lines.

Tags:

5 Responses to “Source lines of code count using PowerShell”

  1. Gary Woodfine Says:

    There are a few syntactical errors in the code supplied therefore it doesn’t appear to work. Thought I would just let you know.

  2. Limilabs support Says:

    @Gary

    What kind of errors? This code works – we’ve used it many times.

  3. Robert Says:

    Your regular expressions really have a problem. 😉 Your spaces aren’t really spaces, because you don’t provide backslashes. Second of all your multi-line comments are included in the count which is also wrong.

    (dir -filter *.cs -recurse | select-string "^\s*$ -notMatch | select-string "^\s*//" -notMatch | select-string "^\s*/\*" -notMatch | select-string "^\s*\*.*(?:\*/)?\s*$" -notMatch).Count

    The last two are of course related to multi-line comments. The first one matches the first line of a multi-line comment, and the second one (last one the list) should match consecutive lines of multi-line comments including the last line. Assuming that consecutive lines start with a “*” in front (as multiline comments usually do).

    This powershell command should do a better lines of code count.

  4. Robert Says:

    … one more thing…

    Whether including opening and closing braces on a separate line should count for the lines of code is a different question altogether. I would say no. They don’t count as a line of code since they do anything really.

    Additional regular expression to exclude them from the lines of code?

    ... | select-string "^\s*(?:\{|\})\s*$" -notMatch

  5. Limilabs support Says:

    @Robert

    You are right – unfortunately WordPress swallows backslashes all the time – corrected.

Questions?

Consider using our Q&A forum for asking any questions.