Powershell代码行数

时间:2014-05-07 07:05:07

标签: regex powershell powershell-v3.0 string-matching

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

<#
    .SYNOPSIS
#>

我自己的评论会阻止

<#
Get-ADUser -Identity ThisUserDoesNotExist
ThisCodeIsCommentedOut
#>

到目前为止我所拥有的是

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

1 个答案:

答案 0 :(得分:2)

如果您使用的是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
}