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.
May 10th, 2016 at 08:57
There are a few syntactical errors in the code supplied therefore it doesn’t appear to work. Thought I would just let you know.
May 10th, 2016 at 09:51
@Gary
What kind of errors? This code works – we’ve used it many times.
May 28th, 2016 at 09:35
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.
May 28th, 2016 at 09:42
… 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
May 28th, 2016 at 11:12
@Robert
You are right – unfortunately WordPress swallows backslashes all the time – corrected.