vs 2022 powershell 统计代码量

只统计 .cs 文件,排除注释(//、///、/* */),空行也一并排除,这是软著源程序量常见的算法。

把下面的脚本在解决方案根目录的 PowerShell 里运行即可:

$pattern = '(?s)@"(?:[^"]|"")*"|"(?:\\.|[^"\\\r\n])*"|''(?:\\.|[^''\\])+''|//[^\r\n]*|/\*.*?\*/'

$files = Get-ChildItem -Recurse -Filter *.cs | Where-Object {
    $_.FullName -notmatch '\\(bin|obj|Migrations)\\' -and
    $_.Name -notmatch '\.(g|g\.i|designer)\.cs$' -and
    $_.Name -notmatch '^(AssemblyInfo|GlobalUsings)'
}

$total = 0
foreach ($f in $files) {
    $text  = Get-Content $f.FullName -Raw -Encoding UTF8
    $clean = [regex]::Replace($text, $pattern, {
        param($m)
        if ($m.Value.StartsWith('//') -or $m.Value.StartsWith('/*')) { '' } else { $m.Value }
    })
    $total += ($clean -split "\r?\n" | Where-Object { $_.Trim() -ne '' }).Count
}

"文件数: $($files.Count)"
"有效代码行数: $total"

 

posted @ 2026-11-05 15:48  小林野夫  阅读(6)  评论(0)    收藏  举报
原文链接:https://www.cnblogs.com/cdaniu/