PowerShell script to report catch blocks

This script will look for catch statements and report a specified number of lines following each catch. It’s a little crude — it prints a fixed number of lines rather than parsing the code well enough to pull out the entire catch block — but it is good enough for code reviews. If there’s a problem, a few lines is usually plenty to spot it. In fact, having less code to look at may help spot problems.

See this blog post: Reviewing catch blocks.

# If path is not provided as an argument,
# the script searches the current directory.

# Make an array of file names in the directory
# containing C# or C++ code
$ext = "\.(cs|cpp|h)$"
$files = (dir -recurse $srcRoot | %{$_.FullName}) -match $ext

# number of lines to print after a catch block
$contextLines = 5

# $contextLines is a guard.
# Initialize $context to any value great than $contextLines
$context = $contextLines + 1 

# Process each file
foreach ($file in $files)
    $allLines = (get-content $file)
    $linesToKeep = @()
    $lineNumber = 0

    # Process each line in a file
    foreach ($line in $allLines)

        if ($line -match "catch\s*\(")
            $linesToKeep += "`nLine $lineNumber"
            $context = 0

        if ($context -le $contextLines)
            $linesToKeep += $line

    # Print report of catch blocks
    if ($linesToKeep.Length -gt 0)
        " "
        " "