Powershell Line Count Utility Tip





5.00/5 (5 votes)
A Powershell command to count lines of code (loc), so I can look it up quicker in the future
Introduction
Ever tried to get a quick LOC (lines of code) count on your project, but Visual Studio only tallies them for managed solutions? And you are grinding away in C++, or another language that isn't supported? Well, here you go, assuming Powershell access!
Background
There is no background to this tip, except I found it on technet: link. I'm only putting it on CodeProject so I can find it here, which is typically quicker than digging through Google again. (Yes, I often search my own articles! And saved a lot of time as a result!)
Using the Code
First, in Explorer, browse to the subdirectory where your code resides. Then type 'powershell
' in the Explorer bar, which will open a copy of Powershell there. Then type:
(dir -include *.cpp, *.h -recurse | select-string "^").Count
To exclude blank lines:
(dir -include *.cpp, *.h -recurse | select-string "^(\s*)$" -notMatch).Count
Or, to also exclude '//
' comments:
(dir -include *.cpp, *.h -recurse | select-string "^(\s*)//" -notMatch |
select-string "^(\s*)$" -notMatch).Count
Change the '*.cpp' and '.h' to whatever file extensions you are interested in. Remove '*.cpp' if you are only interested in headers.
Points of Interest
While typing this up, I found that the original solution counted every character, and my project really didn't have 1.5 million LOC! The corrected attribution link is this one. There is even a version in the comments that strips '/* ... */
' multi-liners.
History
Initial submission: Ground my teeth in frustration upon finding that solution wasn't the solution! Googled and prevailed! (Google-fu search phrase: "powershell count lines code".)
One edit followed, to get the strikethrough working correctly, thanks to a pointer by Sean.