PowerShell Inside All articles
Production Reliability

$Error Is a Crime Scene, Not a Report: A Structured Failure Contract for Production PowerShell

PowerShell Inside
$Error Is a Crime Scene, Not a Report: A Structured Failure Contract for Production PowerShell

Photo: NASA Kennedy Space Center / NASA/John Kraus, Public domain, via Wikimedia Commons

There's a specific kind of dread that comes with opening the transcript from a failed scheduled task and finding forty lines of red text that all say some variation of "Object reference not set to an instance of an object." No file, no target, no hint about what to do next. The script did technically report its failure. It just didn't tell anyone anything.

That's the difference between logging errors and designing a failure contract. $Error is a crime scene — a pile of debris the runtime happened to leave behind. An ErrorRecord you constructed on purpose is a report.

What $Error never tells you

$Error is an automatic, session-scoped collection. In a scheduled task it starts empty, fills up in order, and evaporates when the process exits. It's also limited in size, so early entries roll off during a noisy run. Worse, it captures non-terminating errors too — every Write-Error and every cmdlet that quietly decided not to work. Sorting signal from that pile is guesswork.

The underlying object is better than the collection. Every ErrorRecord carries:

That's a structured record already. The job is to stop throwing it away.

Write-Error is where context goes to die

# The version everyone regrets
try {
    Copy-Item -Path $Source -Destination $Dest -ErrorAction Stop
} catch {
    Write-Error "Copy failed for $Source"
}

Three problems. The catch swallows the original error entirely — $_ is available but unused. Write-Error produces a new record with a generic ID and no inner exception, so the actual cause (permission denied, path missing, disk full) is gone. And the script keeps going, because non-terminating errors don't stop anything, so the next five steps run against a half-copied state.

Throw with intent

Advanced functions get a better tool than throw: $PSCmdlet.ThrowTerminatingError(). It lets you attach a custom, namespaced error ID, a real category, a target object, and the original exception as the inner exception.

function Copy-ReleaseArtifact {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$Source,
        [Parameter(Mandatory)][string]$Destination
    )

    try {
        Copy-Item -LiteralPath $Source -Destination $Destination -ErrorAction Stop
    }
    catch {
        $record = [System.Management.Automation.ErrorRecord]::new(
            [System.IO.IOException]::new(
                "Failed to copy release artifact from '$Source' to '$Destination'.",
                $_.Exception),
            'Contoso.Release.CopyFailed',
            [System.Management.Automation.ErrorCategory]::WriteError,
            $Source)
        $PSCmdlet.ThrowTerminatingError($record)
    }
}

Now callers see Contoso.Release.CopyFailed,Copy-ReleaseArtifact in FullyQualifiedErrorId, the original exception is preserved as InnerException, and the failure is actually terminating. That ID is the contract: it's grep-able in logs, filterable in catch, and stable across refactors of the message text.

Use a prefix that names your org or module. Contoso.Release.CopyFailed tells a support engineer which system owns the problem; CopyFailed tells them nothing.

Catch filters that discriminate

Generic catch {} blocks are the reason scripts have no idea which failure they're handling. Filter on the ID, not the prose:

catch {
    switch -Wildcard ($_.FullyQualifiedErrorId) {
        'Contoso.Release.CopyFailed*'    { Invoke-Retry -Max 3 -Action { Copy-ReleaseArtifact @args } }
        'Contoso.Config.Missing*'       { Write-Fatal -Record $_; exit 78 }
        'System.UnauthorizedAccess*'    { Write-Fatal -Record $_; exit 77 }
        default                         { Write-Fatal -Record $_; exit 1 }
    }
}

Type-based catch [System.IO.IOException] still has its place, but it can't distinguish "disk full" from "file locked." Error IDs can. And because switch -Wildcard matches the trailing ,CommandName, always append the *.

One more trap: exceptions wrapped by throw inside a try, or produced by .NET calls, often carry the real cause in InnerException. Unwrap before you categorize:

$ex = $_.Exception
while ($ex.InnerException) { $ex = $ex.InnerException }
$rootCause = $ex.GetType().FullName

The contract, in five rules

Adopt this as a repo standard and the arguments mostly stop:

  1. Every failure has a namespaced error ID. Org.Area.Reason. No exceptions.
  2. Terminating errors preserve the original exception as InnerException. Never throw "message" over a caught error.
  3. Every catch handles, enriches, or rethrows. Silent swallow is a defect.
  4. Failures leave the process as a structured record plus a non-zero exit code. Schedulers read exit codes; humans read JSON.
  5. Native commands get checked explicitly — $LASTEXITCODE is not an exception. In PowerShell 7.3+, set $PSNativeCommandUseErrorActionPreference = $true so -ErrorAction Stop and try/catch finally apply to robocopy.exe and friends.

For rule 4, emit one record per failure and keep the pipeline clean:

function Write-Fatal {
    param($Record, [string]$CorrelationId = $script:CorrelationId)

    $payload = [ordered]@{
        timestamp     = (Get-Date).ToUniversalTime().ToString('o')
        severity      = 'Error'
        errorId       = $Record.FullyQualifiedErrorId
        category      = $Record.CategoryInfo.Category.ToString()
        target        = [string]$Record.TargetObject
        message       = $Record.Exception.Message
        script        = $Record.InvocationInfo.ScriptName
        line          = $Record.InvocationInfo.ScriptLineNumber
        correlationId = $CorrelationId
    }

    $json = $payload | ConvertTo-Json -Compress
    [Console]::Error.WriteLine($json)
    if ($env:ERROR_LOG_PATH) { Add-Content -Path $env:ERROR_LOG_PATH -Value $json }
}

Writing to the error stream (not stdout) keeps the JSON from poisoning pipeline output, and the correlation ID lets you join this one line against the runbook's job history and whatever the downstream API logged.

Before and after, in one place

# Before: nothing to monitor, nothing to retry, nothing to support
$ErrorActionPreference = 'Continue'
Get-ChildItem $Path | ForEach-Object { Process-Item $_ }

# After
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
try {
    Get-ChildItem -LiteralPath $Path -ErrorAction Stop |
        ForEach-Object { Process-Item -Item $_ -ErrorAction Stop }
} catch {
    Write-Fatal -Record $_
    exit 1
}
exit 0

The second version fails once, fails loudly, identifies the target, and hands your monitoring a line of JSON instead of a paragraph of regret. That's the whole upgrade: stop collecting debris, start filing reports.

All Articles

Related Articles

Nine PowerShell Habits That Pass Code Review and Fail at 3 A.M.

Nine PowerShell Habits That Pass Code Review and Fail at 3 A.M.

4104 at Scale: Turning PowerShell Script Block Logging Into Telemetry Your SOC Will Actually Keep

4104 at Scale: Turning PowerShell Script Block Logging Into Telemetry Your SOC Will Actually Keep

Reading PowerShell's Family Tree: Building Custom AST Rules That Go Beyond PSScriptAnalyzer

Reading PowerShell's Family Tree: Building Custom AST Rules That Go Beyond PSScriptAnalyzer