Modules/businessdev.ALbuild.Core/Private/Get-ALbuildHttpStatusCode.ps1

function Get-ALbuildHttpStatusCode {
    <#
    .SYNOPSIS
        Returns the HTTP status code carried by a failed web request, or 0 when there is none.
 
    .DESCRIPTION
        Separates the two failure modes a web call has: the service answered and refused (a status
        code), or it was never reached (no status - DNS, TLS, timeout, a dropped connection). The
        difference decides both what the user is told and whether retrying can help, so it must not
        be guessed from an exception message.
 
        The exception type differs per host: PowerShell 7 raises HttpResponseException, Windows
        PowerShell 5.1 raises WebException. Both expose the response, but neither property is
        guaranteed to exist on an arbitrary exception, so every hop is read through PSObject to stay
        StrictMode-safe.
 
    .PARAMETER ErrorRecord
        The error record from the failed request.
 
    .OUTPUTS
        Int32. The status code, or 0 when the service was not reached.
    #>

    [CmdletBinding()]
    [OutputType([int])]
    param([Parameter(Mandatory)] $ErrorRecord)

    function Get-Field([object] $Object, [string] $Name) {
        if ($null -eq $Object) { return $null }
        $prop = $Object.PSObject.Properties[$Name]
        if ($prop) { $prop.Value } else { $null }
    }

    $response = Get-Field (Get-Field $ErrorRecord 'Exception') 'Response'
    $status = Get-Field $response 'StatusCode'
    if ($null -eq $status) { return 0 }

    # HttpStatusCode on both hosts; an int on a hand-rolled response object.
    try { return [int] $status } catch { return 0 }
}