1

Im having some trouble counting the lines of code in all my powershell projects. I want to ignore comment sections in my count, unfortunately I am not that good with regular expressions. So what I want to achieve is to exclude all the "Synopsis help code in functions"

<#
    .SYNOPSIS
#>

And my own comment blocks

<#
Get-ADUser -Identity ThisUserDoesNotExist
ThisCodeIsCommentedOut
#>

What I have so far is

Get-Content Script.ps1 | ?{$_ -ne "" -and $_ -notlike "#*"}
2
  • Think I found a way round it: function Count-CommentBlock { param ( $ScriptText ) $boolInsideComment = $false $lineCounter = 0 $lineTotal = 0 $ScriptText = $ScriptText.Trim() foreach ($Line in $ScriptText) { if ($Line -like "<#*") { $boolInsideComment = $true } elseif ($Line -like "#>*") { $boolInsideComment = $false $lineCounter++ $lineTotal += $lineCounter } if ($boolInsideComment) { $lineCounter++ } } return $lineTotal } This should work? Commented May 7, 2014 at 7:59
  • why not using my solution? Commented May 7, 2014 at 9:00

1 Answer 1

2

If you are in v3.0 I suggest to use this script: http://poshcode.org/4789

Here the relevant part modified just to count lines of code of a script file:

$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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.