- Courses
- 💻Programming Languages
- 🪟PowerShell
- Scripting Fundamentals
- Error Handling & Debugging
- Terminating vs. Non-Terminating Errors
On this page
PowerShell Error Handling – Terminating, Non-Terminating, and Everything In Between
Updated on June 16, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
PowerShell has three categories of errors — non-terminating, statement-terminating, and script-terminating — and each behaves differently when it occurs. Most cmdlet failures produce non-terminating errors that let the script continue, while throw and missing commands produce script-terminating errors that unwind the entire call stack. The mechanism that connects these two worlds is -ErrorAction Stop and $ErrorActionPreference, which promote non-terminating errors into terminating ones so that try/catch can intercept them. Every tool in the error handling system — try/catch/finally, trap, Write-Error, $Error, $?, and $ErrorActionPreference — builds on this model.
The Three Error Categories
Non-terminating errors
A non-terminating error reports a problem but allows the script to continue running. The cmdlet writes the error to the error stream and moves on to the next object in the pipeline. Most cmdlets produce non-terminating errors for recoverable situations:
Remove-Item "C:\NonExistentFile.txt"
"Script continues here"
Remove-Item writes a red error message to the console because C:\NonExistentFile.txt does not exist. Then execution continues and "Script continues here" is output. The error does not stop the script.
Non-terminating errors exist because bulk operations should not fail entirely when one item fails. Deleting 100 files should continue even if three of them are already gone. The pattern allows processing the remaining 97 while recording the three failures.
Statement-terminating errors
A statement-terminating error stops the current statement from running but allows PowerShell to continue at the next statement. These are generated internally by compiled cmdlets when they call $PSCmdlet.ThrowTerminatingError() — they are more severe than a non-terminating error but less severe than a script-terminating error.
Get-Item "C:\NoSuchPath\" # statement-terminating — stops this statement
"Next statement runs" # this executes despite the error above
The distinction from script-terminating errors matters for try/catch behaviour, discussed below.
Script-terminating errors
A script-terminating error unwinds the entire call stack. Execution stops completely unless the error is caught by a try/catch block or a trap statement. Script-terminating errors are generated by:
- The
throwkeyword - Parse errors and syntax errors
- Missing command names (e.g., calling
NoSuchCommand) - Non-terminating errors escalated by
-ErrorAction Stopor$ErrorActionPreference = 'Stop'in a non-advanced context
throw "Critical failure"
"This never runs"
throw produces a script-terminating error immediately. Everything after it is unreachable unless there is a surrounding try/catch.
$ErrorActionPreference — Controlling Error Behaviour Globally
$ErrorActionPreference is a preference variable that controls how PowerShell responds to non-terminating errors throughout the current scope. It accepts six values:
ValueBehaviourContinueDisplay the error and continue executing. This is the default.StopEscalate the non-terminating error to a terminating error and stop executionSilentlyContinueSuppress the error message, continue executing, but still add the error to $Error``IgnoreSuppress the error message, continue executing, and do not add the error to $Error``InquireDisplay the error and prompt the user for a decision before continuingBreakEnter the debugger when an error occurs
$ErrorActionPreference = "Stop"
Remove-Item "C:\NonExistentFile.txt" # now terminates instead of continuing
"This never runs"
Setting $ErrorActionPreference = 'Stop' at the top of a script makes every non-terminating error behave as a terminating error, which means try/catch can intercept all failures without adding -ErrorAction Stop to every individual command. This is a common pattern for deployment and administrative scripts where any failure should halt execution.
Be aware that $ErrorActionPreference is scope-specific. A child scope (a called function) may have a different value. Set it explicitly inside the scope where you need the behaviour.
-ErrorAction — Controlling Error Behaviour Per Command
The -ErrorAction common parameter (alias -ea) overrides $ErrorActionPreference for a single command. It accepts the same six values and takes precedence over the session preference for that specific command:
$ErrorActionPreference = "Continue"
# This specific command is forced to stop on error despite the global preference
Remove-Item "C:\NonExistentFile.txt" -ErrorAction Stop
"This never runs because -ErrorAction Stop caused a terminating error"
Use -ErrorAction SilentlyContinue to suppress known, expected failures without affecting the rest of the script:
# Attempt to stop a service that may or may not be running — suppress the error if it is not
Stop-Service -Name "SomeOptionalService" -ErrorAction SilentlyContinue
Use -ErrorAction Stop when you want to catch a specific cmdlet's failure with try/catch:
try {
Get-Content "C:\missing.txt" -ErrorAction Stop
}
catch {
"Caught the file read error: $($_.Exception.Message)"
}
try/catch/finally — Structured Error Handling
try/catch only handles terminating errors. Non-terminating errors flow straight through the try block without triggering any catch. Always pair try/catch with -ErrorAction Stop or $ErrorActionPreference = 'Stop' when handling cmdlet failures.
Basic try/catch
try {
Remove-Item "C:\NonExistentFile.txt" -ErrorAction Stop
}
catch {
"An error occurred: $($_.Exception.Message)"
}
Remove-Item would normally produce a non-terminating error and continue. The -ErrorAction Stop parameter escalates it to a terminating error. The catch block intercepts it. $_ inside catch is an ErrorRecord object whose .Exception.Message property contains the human-readable error description. Output: An error occurred: Cannot find path 'C:\NonExistentFile.txt' because it does not exist.
Typed catch blocks — catching specific exceptions
You can catch specific .NET exception types by specifying the type in square brackets after catch. More specific exception types must appear before more general ones:
try {
Get-Content "C:\missing.txt" -ErrorAction Stop
}
catch [System.IO.FileNotFoundException] {
"File not found: $($_.Exception.Message)"
}
catch [System.UnauthorizedAccessException] {
"Permission denied: $($_.Exception.Message)"
}
catch {
"Unexpected error: $($_.Exception.Message)"
}
PowerShell evaluates catch blocks in order. The first matching type wins. The unqualified catch at the end acts as a catch-all for any terminating error not matched by a specific type. This structure allows different responses to different failure modes in the same block.
To discover the exception type of an error, inspect $_.Exception.GetType().FullName inside a catch block:
try {
Get-Content "C:\missing.txt" -ErrorAction Stop
}
catch {
$_.Exception.GetType().FullName
# System.Management.Automation.ItemNotFoundException
}
The ActionPreferenceStopException wrapper
When -ErrorAction Stop or $ErrorActionPreference = 'Stop' escalates a non-terminating error, PowerShell wraps it in an ActionPreferenceStopException. The original error information is accessible through $_.Exception.ErrorRecord:
try {
Get-Item "C:\NonExistent" -ErrorAction Stop
}
catch [System.Management.Automation.ActionPreferenceStopException] {
$originalError = $_.Exception.ErrorRecord
"Original error: $($originalError.Exception.Message)"
}
catch {
"Other error: $($_.Exception.Message)"
}
In practice, the unqualified catch is simpler and sufficient for most use cases. The typed ActionPreferenceStopException catch is only needed when you must distinguish escalated non-terminating errors from native terminating errors.
The finally block
Code in the finally block always executes — whether the try block succeeded, a catch handled an error, or an uncaught error propagated up the call stack. It is the correct place for cleanup logic that must run regardless of outcome:
$connection = $null
try {
$connection = [System.Data.SqlClient.SqlConnection]::new("connection string")
$connection.Open()
# ... database work ...
"Operation completed"
}
catch {
"Database error: $($_.Exception.Message)"
}
finally {
if ($null -ne $connection -and $connection.State -eq 'Open') {
$connection.Close()
"Connection closed in finally block"
}
}
The finally block closes the database connection even if the try block threw an uncaught error that is propagating up. Without finally, an error during database work would leave the connection open.
Re-throwing errors
Inside a catch block, throw with no argument re-throws the current exception, preserving the original error record:
try {
Get-Item "C:\missing.txt" -ErrorAction Stop
}
catch [System.IO.FileNotFoundException] {
Write-Warning "File not found — logging and re-throwing"
# log the error here
throw # re-throw the original exception unchanged
}
throw with no argument is the correct mechanism for logging an error and propagating it to the caller. Using throw $_ also works but creates a new exception that wraps the original, which can change the exception type visible to the caller's catch block.
Write-Error — Generating Non-Terminating Errors
Write-Error is the cmdlet-equivalent mechanism for generating non-terminating errors from your own functions. It writes an ErrorRecord to the error stream, just like built-in cmdlets do internally:
function Get-ValidUser {
[CmdletBinding()]
param([string]$Username)
if ([string]::IsNullOrEmpty($Username)) {
Write-Error "Username cannot be empty."
return
}
"Processing user: $Username"
}
Get-ValidUser -Username ""
"Script continues after the non-terminating error"
Write-Error displays the error message in red but the script continues. The caller can control how it responds to the error using -ErrorAction on the function call:
try {
Get-ValidUser -Username "" -ErrorAction Stop
}
catch {
"Caught the Write-Error: $($_.Exception.Message)"
}
Write-Error sets $? to $false immediately after execution. This is how callers can check whether the last command succeeded without using exceptions.
throw — Generating Script-Terminating Errors
throw generates a script-terminating error. It accepts a string, an exception object, or an ErrorRecord object. When used inside a catch block with no argument, it re-throws the current exception:
# throw with a string
throw "Configuration file not found"
# throw with an exception object
throw [System.IO.FileNotFoundException]::new("C:\config.json not found")
# throw with a custom exception type
throw [System.ArgumentException]::new("The value must be between 1 and 100.", "RetentionDays")
Each produces a script-terminating error that can be caught by try/catch. The message string "Configuration file not found" appears as the exception message. Throwing a specific .NET exception type allows callers to write typed catch blocks that target it precisely.
$ErrorActionPreference = 'SilentlyContinue' can suppress throw — making it behave as if no error occurred and execution continues at the next statement. This is a documented but rarely expected behaviour. Avoid relying on it.
$Error — The Error History
$Error is an automatic variable that holds an ArrayList of the most recent error records in the session, with the most recent at index [0]. PowerShell keeps up to $MaximumErrorCount entries (default: 256):
# Generate some errors
Get-Item "C:\missing1.txt" -ErrorAction SilentlyContinue
Get-Item "C:\missing2.txt" -ErrorAction SilentlyContinue
# Inspect the most recent error
$Error[0].Exception.Message # describes the last error
$Error[0].CategoryInfo.Category # ObjectNotFound
$Error[0].InvocationInfo.Line # the line of code that caused it
# Count errors in the current session
$Error.Count
# Clear the error list
$Error.Clear()
SilentlyContinue suppresses the error message but still records it in $Error. Only Ignore suppresses both the message and the $Error recording.
Use $Error for post-mortem debugging and for logging all errors from a section of code:
$Error.Clear()
# Run a series of operations that may fail
"Server01", "Server02", "MissingServer" | ForEach-Object {
Test-Connection -ComputerName $_ -Count 1 -Quiet -ErrorAction SilentlyContinue
}
# After all operations, inspect what failed
if ($Error.Count -gt 0) {
$Error | ForEach-Object {
"$($_.InvocationInfo.ScriptLineNumber): $($_.Exception.Message)"
}
}
$? — The Last Success Indicator
$? is a boolean automatic variable that indicates whether the last command succeeded. It is $true if the last command did not produce an error and $false if it did:
Get-Item "C:\ExistingFile.txt"
$? # True — command succeeded
Get-Item "C:\NonExistentFile.txt" -ErrorAction SilentlyContinue
$? # False — command produced an error
$? is useful for lightweight error checking without try/catch:
Copy-Item "C:\Source\data.csv" "C:\Dest\" -ErrorAction SilentlyContinue
if (-not $?) {
Write-Warning "Copy failed — check $($Error[0].Exception.Message)"
}
Note that $? reflects the result of the last command in the scope at the exact point it is read. Calling any command between the failing operation and the $? check will overwrite it.
trap — Scope-Level Error Handling
trap is an alternative to try/catch that handles terminating errors at the scope level rather than the block level. It is inherited from PowerShell's early versions and remains useful for wrapping an entire script:
trap {
"Trapped error: $($_.Exception.Message)"
continue # continue execution after the statement that caused the error
}
1 / 0
"This runs because 'continue' was used in the trap"
throw "Fatal"
"This also runs because the trap continues"
The continue keyword inside a trap tells PowerShell to continue execution after the statement that caused the error. Without continue or break, the trap executes and then re-throws the error to the parent scope.
trap processes all terminating errors in its scope, including those from called functions. This makes it suitable for top-level error logging in a script:
trap {
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
"$timestamp ERROR: $($_.Exception.Message)" |
Add-Content -Path "C:\Logs\script_errors.log"
break # stop execution after logging
}
# All terminating errors in this script are now logged automatically
break inside trap stops execution at the current scope level after running the trap block.
When both a trap and a try/catch are in scope for the same error, try/catch takes precedence when the error occurs inside the try block. The trap only runs for errors outside any try/catch block.
Custom Exceptions
PowerShell can throw and catch any .NET exception class. Defining a custom exception gives callers a precise type to target:
# Define a custom exception class using Add-Type
Add-Type -TypeDefinition @"
using System;
public class DeploymentException : Exception {
public string Environment { get; }
public DeploymentException(string message, string environment)
: base(message) {
Environment = environment;
}
}
"@
function Deploy-Application {
[CmdletBinding()]
param([string]$Environment)
if ($Environment -eq "Production" -and -not $ApprovalGranted) {
throw [DeploymentException]::new(
"Production deployment requires approval.",
$Environment
)
}
"Deploying to $Environment"
}
try {
Deploy-Application -Environment "Production"
}
catch [DeploymentException] {
"Deployment blocked for '$($_.Exception.Environment)': $($_.Exception.Message)"
}
catch {
"Unexpected error: $($_.Exception.Message)"
}
Add-Type compiles the C# class definition and makes it available in the session. The custom exception carries the Environment property, which the catch block accesses through $_.Exception.Environment. Typed catch blocks make the error handling intent explicit and allow different code paths for different failure modes.
Logging Errors to a File
Structured error logging is a production requirement for any unattended script. Log both the error detail and the context:
function Write-ErrorLog {
param(
[System.Management.Automation.ErrorRecord]$ErrorRecord,
[string]$LogPath = "C:\Logs\errors.log"
)
$entry = [PSCustomObject]@{
Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Message = $ErrorRecord.Exception.Message
Category = $ErrorRecord.CategoryInfo.Category
ScriptLine = $ErrorRecord.InvocationInfo.ScriptLineNumber
Command = $ErrorRecord.InvocationInfo.Line.Trim()
}
$entry | Export-Csv -Path $LogPath -Append -NoTypeInformation
}
try {
Get-Content "C:\missing.txt" -ErrorAction Stop
}
catch {
Write-ErrorLog -ErrorRecord $_ -LogPath "C:\Logs\errors.log"
"Logged and continuing"
}
Write-ErrorLog accepts the ErrorRecord object from the catch block and writes a structured CSV row. Each row includes the timestamp, message, error category, script line number, and the exact command that failed. This format is machine-readable and easy to query later.
Complete Error Handling Reference
MechanismWhat it doesNon-terminating errorWrites to error stream, continues executionStatement-terminating errorStops current statement, continues at nextScript-terminating errorUnwinds call stack, stops script unless caught-ErrorAction StopEscalates non-terminating error to terminating for one command$ErrorActionPreferenceSets default error behaviour for the current scopetry/catchCatches terminating errors in a specific blockcatch [Type]Catches specific exception typesfinallyRuns cleanup code regardless of success or failurethrowGenerates a script-terminating errorWrite-ErrorGenerates a non-terminating errortrapCatches terminating errors at the scope level$ErrorArray of recent error records ($Error[0] = most recent)$?``$true if last command succeeded, $false if it failed
Common Mistakes to Avoid
Using try/catch without -ErrorAction Stop on cmdlets. try/catch only catches terminating errors. Most cmdlet failures are non-terminating and flow right past the try block invisibly. Always add -ErrorAction Stop to cmdlets inside a try block.
Setting $ErrorActionPreference = 'Stop' globally in a large script. This escalates every non-terminating error everywhere, including inside called functions and modules that may produce expected non-terminating errors. Scope it carefully or use per-command -ErrorAction Stop.
Reading $? after other commands. $? reflects the result of the most recently executed command. Any command between the operation you want to check and the $? read overwrites it. Check $? immediately after the command being evaluated.
Swallowing errors without logging. An empty catch { } block silences the error but leaves no evidence. Always log at minimum to $Error or a file so failures are traceable.
Using SilentlyContinue when Ignore is needed. If $Error is being used for post-mortem analysis, SilentlyContinue is correct — it still records to $Error. Ignore is for when the error truly does not matter and even the $Error entry is noise.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Error Handling & Debugging
Next
Try, Catch & Finally
-
The Three Error Categories
- Non-terminating errors
- Statement-terminating errors
- Script-terminating errors
-
$ErrorActionPreference— Controlling Error Behaviour Globally -
-ErrorAction— Controlling Error Behaviour Per Command -
try/catch/finally— Structured Error Handling- Basic try/catch
- Typed catch blocks — catching specific exceptions
- The
ActionPreferenceStopExceptionwrapper - The
finallyblock - Re-throwing errors
-
Write-Error— Generating Non-Terminating Errors -
throw— Generating Script-Terminating Errors -
$Error— The Error History -
$?— The Last Success Indicator -
trap— Scope-Level Error Handling -
Custom Exceptions
-
Logging Errors to a File
-
Complete Error Handling Reference
-
Common Mistakes to Avoid
