Use Powershell to print out line number of code matching a RegEx Use Powershell to print out line number of code matching a RegEx powershell powershell

Use Powershell to print out line number of code matching a RegEx


You could do:

dir c:\codeishere -filter *.cs -recurse | select-string -Pattern '//.*;' | select Line,LineNumber,Filename


gci c:\codeishere *.cs -r | select-string "//.*;"

The select-string cmdlet already does exactly what you're asking for, though the filename displayed is a relative path.


I would go personally even further. I would like to compute number of consecutive following lines. Then print the file name, count of lines and the lines itself. You may sort the result by count of lines (candidates for delete?).Note that my code doesn't count with empty lines between commented lines, so this part is considered as two blocks of commented code:

// int a = 10;// int b = 20;// DoSomething()// SomethingAgain()

Here is my code.

$Location = "c:\codeishere"$occurences = get-ChildItem $Location *cs -recurse | select-string '//.*;'$grouped = $occurences | group FileNamefunction Compute([Microsoft.PowerShell.Commands.MatchInfo[]]$lines) {  $local:lastLineNum = $null  $local:lastLine = $null  $local:blocks = @()  $local:newBlock = $null  $lines |     % {       if (!$lastLineNum) {                             # first line        $lastLineNum = -2                              # some number so that the following if is $true (-2 and lower)      }      if ($_.LineNumber - $lastLineNum -gt 1) {        #new block of commented code        if ($newBlock) { $blocks += $newBlock }        $newBlock = $null      }      else {                                           # two consecutive lines of commented code        if (!$newBlock) {           $newBlock = '' | select File,StartLine,CountOfLines,Lines          $newBlock.File, $newBlock.StartLine, $newBlock.CountOfLines, $newBlock.Lines = $_.Filename,($_.LineNumber-1),2, @($lastLine,$_.Line)        }        else {          $newBlock.CountOfLines += 1          $newBlock.Lines += $_.Line        }      }      $lastLineNum=$_.LineNumber      $lastLine = $_.Line    }  if ($newBlock) { $blocks += $newBlock }  $blocks}# foreach GroupInfo objects from group cmdlet# get Group collection and compute $result = $grouped | % { Compute $_.Group }#how to print$result | % {  write-host "`nFile $($_.File), line $($_.StartLine), count of lines: $($_.CountOfLines)" -foreground Green  $_.Lines | % { write-host $_ }}# you may sort it by count of lines:$result2 = $result | sort CountOfLines -desc$result2 | % {  write-host "`nFile $($_.File), line $($_.StartLine), count of lines: $($_.CountOfLines)" -foreground Green  $_.Lines | % { write-host $_ }}

If you have any idea how to improve the code, post it! I have a feeling that I could do it using some standard cmdlets and the code could be shorter..