I would personally go even further. I would like to calculate the number of consecutive lines. Then print the file name, number of lines and line. You can sort the result by the number of rows (candidates for deletion?). Please note that my code does not count with empty lines between comments, so this part is considered as two blocks of code with comments:
// 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 FileName function 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 }
If you have an idea how to improve the code, post it! I have the feeling that I can do this with some standard cmdlets, and the code may be shorter.
source share