【问题标题】:Powershell Lines of code countPowershell 代码行数
【发布时间】:2014-06-24 00:39:51
【问题描述】:

我在计算所有 powershell 项目中的代码行数时遇到了一些麻烦。 我想忽略我的计数中的评论部分,不幸的是我对正则表达式不太擅长。 所以我想要实现的是排除所有“函数中的概要帮助代码”

<#
    .SYNOPSIS
#>

还有我自己的评论区

<#
Get-ADUser -Identity ThisUserDoesNotExist
ThisCodeIsCommentedOut
#>

到目前为止我所拥有的是

Get-Content Script.ps1 | ?{$_ -ne "" -and $_ -notlike "#*"}

【问题讨论】:

  • 我想我找到了解决方法: function Count-CommentBlock { param ( $ScriptText ) $boolInsideComment = $false $lineCounter = 0 $lineTotal = 0 $ScriptText = $ScriptText.Trim() foreach ( $Line in $ScriptText) { if ($Line -like "*") { $boolInsideComment = $false $lineCounter++ $lineTotal += $lineCounter } if ($boolInsideComment) { $lineCounter++ } } return $lineTotal } 这应该有效吗?
  • 为什么不使用我的解决方案?

标签: regex powershell powershell-3.0 string-matching


【解决方案1】:

如果您使用的是 v3.0,我建议使用此脚本:http://poshcode.org/4789

这里修改的相关部分只是为了计算脚本文件的代码行数:

$file = ".\My_Script_File.ps1"

$fileContentsArray  = Get-Content -Path $file

if ($fileContentsArray)
    {
        $codeLines          = $null
        $tokenAst           = $null
        $parseErrorsAst     = $null
        # Use the PowerShell 3 file parser to create the scriptblock AST, tokens and error collections
        $scriptBlockAst     = [System.Management.Automation.Language.Parser]::ParseFile($file, [ref]$tokenAst, [ref]$parseErrorsAst)
        # Calculate the 'lines of code': any line not containing comment or commentblock and not an empty or whitespace line.
        # Remove comment tokens from the tokenAst, remove all double newlines and count all the newlines (minus 1)
        $prevTokenIsNewline = $false
        $codeLines      = @($tokenAst | select -ExpandProperty Kind |  where { $_ -ne "comment" } | where {
                                if ($_ -ne "NewLine" -or (!$prevTokenIsNewline))
                                {
                                    $_
                                }
                            $prevTokenIsNewline = ($_ -eq "NewLine")
                            } | where { $_ -eq "NewLine" }).Length-1
    $codeLines
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多