OSPowerShell.009: PowerShell Error Handling — Try, Catch, Finally and ErrorAction

A young infrastructure engineer working at a terminal with branching error-handling paths.

Open-Source PowerShell • Intermediate • Estimated study time: 35 minutes.

Infrastructure automation must distinguish a failed operation from a completed operation that returned no data. A script that ignores a failed configuration read may proceed with invalid assumptions. Building upon PowerShell functions and parameter validation, learners will construct explicit error paths, inspect error records and perform cleanup without modifying production infrastructure.

Prerequisites and learning objectives

Use PowerShell 7 in a disposable local directory with ordinary user permissions. Review cmdlets and Get-Help. By the end, distinguish terminating and non-terminating errors, escalate a cmdlet error with ErrorAction, inspect an ErrorRecord, use finally for cleanup and rethrow an unexpected failure.

Terminating and non-terminating errors

PowerShell commands may report a non-terminating error while continuing to process remaining input. A terminating error interrupts the affected statement or script and can transfer control to a matching catch block. For cmdlets supporting common parameters, -ErrorAction Stop escalates a non-terminating error into one that catch can handle. The Microsoft error-handling reference documents these distinctions.

The following original tutorial demonstrates the try, catch and finally control structures:

The tutorial demonstrates exception handling and separate catch clauses for PowerShell errors. Watch at source.

Laboratory: read a configuration safely

Create a uniquely named temporary directory and a sample file, then execute the following code. No administrator rights or production paths are required:

$lab = Join-Path ([System.IO.Path]::GetTempPath()) ([guid]::NewGuid().ToString())
New-Item -ItemType Directory -Path $lab -ErrorAction Stop | Out-Null
try {
    $path = Join-Path $lab 'config.txt'
    Set-Content -LiteralPath $path -Value 'mode=lab' -ErrorAction Stop
    Get-Content -LiteralPath $path -ErrorAction Stop
    Get-Content -LiteralPath (Join-Path $lab 'missing.txt') -ErrorAction Stop
    'Unreachable after failed read'
}
catch [System.Management.Automation.ItemNotFoundException] {
    'Missing configuration file'
}
finally {
    Remove-Item -LiteralPath $lab -Recurse -Force -ErrorAction Stop
    'Cleanup complete'
}

The expected output is:

mode=lab
Missing configuration file
Cleanup complete

The first read succeeds. The second encounters a nonexistent path, so ErrorAction Stop transfers control to the typed catch. The finally clause removes only the GUID-named laboratory directory. Do not replace the temporary directory variable with a production path. Compare the control transfer with conditional branching. The output is predicted from documented semantics, not an executed runtime test.

Inspecting and propagating unexpected errors

Inside catch, $_ represents the current error record. Its Exception, FullyQualifiedErrorId and CategoryInfo properties provide diagnostic context. Avoid suppressing unexpected faults merely to keep automation running. Use a bare throw to propagate the current error to the caller. The following function illustrates that pattern:

function Read-LabConfig {
    param([string]$Path)
    try {
        Get-Content -LiteralPath $Path -ErrorAction Stop
    }
    catch {
        Write-Warning $_.FullyQualifiedErrorId
        throw
    }
}

A caller can decide whether to retry, use a documented fallback or terminate the job. Review PowerShell objects and Get-Member to inspect error-record properties. Do not assume that native executable exit codes follow the same rules; inspect $LASTEXITCODE or explicitly configure and test native-command handling for your PowerShell version.

The following supplementary lesson covers ErrorAction, throw and diagnostic commands:

The instructor explains script error handling and diagnostic commands for PowerShell automation. Watch at source.

Exercises and answer key

1. Explain why the missing file enters catch. 2. Predict the effect of replacing Stop with Continue in the failed read. 3. Identify the cleanup clause. 4. Explain why a bare throw is appropriate for an unexpected error.

Answers: 1. Stop escalates the cmdlet error. 2. Under the ordinary Continue preference, the non-terminating error is reported and the following string executes. 3. Finally runs when control leaves the try/catch construct. 4. It propagates failure instead of falsely reporting success.

Conclusion

Reliable automation treats failure as an explicit control-flow outcome. Use narrowly scoped recovery, inspect error records and release resources predictably. Consult the Microsoft try/catch/finally reference before integrating the pattern into a production script.

We volunteer daily to ensure the credibility of the information on the platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiative, please scan the QR code below.

BitcoinVersus.Tech donation QR code

Leave a Reply