Modules/businessdev.ALbuild.Core/Public/Format-BcErrorMessage.ps1

function Format-BcErrorMessage {
    <#
    .SYNOPSIS
        Reduces a captured PowerShell error rendering to its core, human-readable message.
 
    .DESCRIPTION
        Error text captured from a child process or an in-container command arrives wrapped in
        PowerShell's error-view scaffolding - the offending source line, the '~~~~' underline,
        'At line:N char:M', and the '+ CategoryInfo' / '+ FullyQualifiedErrorId' trailers - often
        nested twice (in-container error rendered, then re-thrown and rendered again) and coloured
        with ANSI escapes. Dumped into a build log this buries the actual reason. This strips the
        scaffolding and returns just the message so logs are readable. Plain text without scaffolding
        is returned unchanged, so it is always safe to call.
 
    .PARAMETER Text
        The captured error text.
 
    .OUTPUTS
        System.String
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param(
        [AllowNull()] [AllowEmptyString()]
        [string] $Text
    )

    if ([string]::IsNullOrWhiteSpace($Text)) { return $Text }

    # Drop ANSI colour escapes first so the line matches below are reliable.
    $t = [regex]::Replace($Text, "$([char]27)\[[0-9;]*[A-Za-z]", '')

    # Keep only the message text, dropping the error-view scaffolding lines (PS7 ConciseView and
    # Windows PowerShell NormalView both produce these).
    $kept = [System.Collections.Generic.List[string]]::new()
    foreach ($raw in ($t -split "`r?`n")) {
        $line = $raw.Trim()
        if (-not $line) { continue }
        if ($line -match '^Exception:') { continue }                         # ConciseView header
        if ($line -match '^Line \|$') { continue }                           # ConciseView 'Line |'
        if ($line -match '^\d+ \|') { continue }                             # the offending source line
        if ($line -match '^\|\s*~+\s*$') { continue }                        # the '~~~~' underline
        if ($line -match '^\+') { continue }                                 # NormalView '+ ' echo/underline/CategoryInfo/FullyQualifiedErrorId
        if ($line -match '^At line:\d+ char:\d+') { continue }
        $line = $line -replace '^\|\s?', ''                                  # ConciseView wraps message with '| '
        $kept.Add($line)
    }

    $msg = ($kept -join ' ')
    # Cut any positional/category trailers that share a line with the message. Cutting at the first
    # 'At line:' removes everything PowerShell appended after the message in one go.
    $msg = $msg -replace '\s*At line:\d+ char:\d+.*$', ''
    $msg = $msg -replace '\s*\+\s*CategoryInfo\b.*$', ''
    $msg = $msg -replace '\s*\+\s*FullyQualifiedErrorId\b.*$', ''
    $msg = ($msg -replace '\s+', ' ').Trim()

    # Never return empty when we were given content.
    if (-not $msg) { return $Text.Trim() }
    return $msg
}