ConvertTo-Breakpoint.psm1

Write-Verbose 'Importing from [C:\projects\convertto-breakpoint\Module\private]'
# .C:\projects\convertto-breakpoint\Module\private\ExtractBreakpoint.ps1
function ExtractBreakpoint
{
    <#
    .DESCRIPTION
    Parses a script stack trace for breakpoints

    .EXAMPLE
    $error[0].ScriptStackTrace | ExtractBreakpoint
    #>

    [OutputType('System.Collections.Hashtable')]
    [cmdletbinding()]
    param(
        # The ScriptStackTrace
        [parameter(
            ValueFromPipeline
        )]
        [AllowNull()]
        [AllowEmptyString()]
        [Alias('InputObject')]
        [string]
        $ScriptStackTrace
    )

    begin
    {
        $breakpointPattern = 'at .+, (?<Script>.+): line (?<Line>\d+)'
    }

    process
    {
        if (-not [string]::IsNullOrEmpty($ScriptStackTrace))
        {
            $lineList = $ScriptStackTrace -split [System.Environment]::NewLine
            foreach($line in $lineList)
            {
                if ($line -match $breakpointPattern)
                {
                    if ($matches.Script -ne '<No file>' -and 
                        (Test-Path $matches.Script))
                    {
                        @{
                            Script = $matches.Script
                            Line   = $matches.Line
                        }                                
                    }
                }
            }
        }
    }
}

Write-Verbose 'Importing from [C:\projects\convertto-breakpoint\Module\public]'
# .C:\projects\convertto-breakpoint\Module\public\ConvertTo-Breakpoint.ps1
function ConvertTo-Breakpoint
{
    <#
        .DESCRIPTION
        Converts an errorrecord to a breakpoint

        .Example
        $error[0] | ConvertTo-Breakpoint

        .Example
        $error[0] | ConvertTo-Breakpoint -All
    #>

    [CmdletBinding(SupportsShouldProcess)]
    param(
        # The error record
        [parameter(
            Mandatory,
            Position = 0,
            ValueFromPipeline
        )]
        [Alias('InputObject')]
        $ErrorRecord,

        # Sets breakpoints on the entire stack
        [switch]
        $All
    )

    process
    {
        foreach ($node in $ErrorRecord)
        {
            $breakpointList = $node.ScriptStackTrace | ExtractBreakpoint

            foreach ($breakpoint in $breakpointList)
            {
                $message = '{0}:{1}' -f $breakpoint.Script,$breakpoint.Line
                if($PSCmdlet.ShouldProcess($message))
                {
                    Set-PSBreakpoint @breakpoint
                    if (-Not $PSBoundParameters.All)
                    {
                        break
                    }
                }
            }                
        }
    }
}

Write-Verbose 'Importing from [C:\projects\convertto-breakpoint\Module\classes]'