PowerShell Error Handling: Practical Tips and Examples 

PowerShell error handling isn’t about fixing a bug after deployment. It’s about anticipating what might go wrong within a PowerShell script and setting up guardrails that prevent script malfunction or failure. 

Script failures can occur even if you have years of experience writing code and a keen eye for detail. Sometimes, the code is solid, but the logic is flawed. Or an external source — like a computer or database — is unavailable when your code attempts to query it. Fortunately, PowerShell commands can help you prevent common errors in code. 

Terminating vs. non-terminating errors

PowerShell errors fall into two categories: 

  • Terminating — These errors cause the code to crash. An example of a terminating error is an “exception” that terminates code execution — like an erroneous space in a command line. 
  • Non-terminating errors — These errors interfere with script functionality but don’t terminate execution. You can, however, promote non-terminating errors to terminating errors using the -ErrorAction Stop command.

PowerShell exceptions

Exceptions are PowerShell’s method for triaging errors thrown during the processing of commands and scripts. They provide a mechanism for identifying the error type, its source, and the specific nature of the problem. Here’s a more detailed breakdown:

Syntax errors

Syntax errors occur when the script does not conform to language rules. That can be as simple as failing to include an opening or closing bracket. 

Runtime errors 

Runtime errors occur when the script is correct but encounters an unexpected issue, like incompatible data formats or insufficient memory.

PowerShell try/catch/finally commands

PowerShell uses the try/catch/finally structure to encapsulate blocks of code and handle exceptions systematically. Within this framework, you can separate the logic for normal execution and error handling.

To get started with error handling in PowerShell, look for sources of potential error in your code — like any Get-Command that queries sources or files outside of your code. Then: 

1. Use a try command to test the code — put the code you’ve identified inside a try block

2. Use a catch command — specify what should happen if the code in the try block triggers an exception

3. Use a finally command — this command defines:

  • What happens after the try command, if there was no exception

-or-

  • What happens after the catch command, if there was an exception

Here’s an example:

try {

# code that may cause an error

$fileContent = Get-Content -Path “C:\Documents\Reports\December2024.csv”

catch 

{

# specific action if the file is not found

Write-Host “File not found. Please check the file path.”

}

finally

{

# code that runs regardless of success or failure

Write-Host “Finished attempting to read the file.”

}

PowerShell error logging

In PowerShell, errors are not automatically logged to persistent storage like files or system event logs by default. However, PowerShell does store error information in the $Error Variable, which contains details of errors encountered during the current session or script execution.

The $Error Variable holds the current-session errors but that information doesn’t carry over to new sessions. If you want to capture and log all errors, you’ll need to use PowerShell error logging code to sync with your event log.

Here’s an example of basic error logging:

$timestamp = Get-Date -Format “yyyy-MM-dd HH:mm:ss”

$errorLog = “C:\PowerShell\ErrorLog.txt”

try {

    # Potential error-causing operation

    Get-Content -Path “C:\NonexistentFile.txt”

}

catch {

    # Log error details to a file

    $errorMessage = “$timestamp – Error: $($_.Exception.Message)”

    Add-Content -Path $errorLog -Value $errorMessage

    Write-Host “An error occurred and was logged.”

}

Swallowing exceptions in PowerShell

So far, we’ve focused on how to prevent and record errors. But there’s another option: ignoring (swallowing) errors. You can do that with this command: 

-ErrorAction SilentlyContinue

Ignoring an error is a risky move, because PowerShell will suppress the error as if it never occurred and therefore won’t log error details. But there may be times when swallowing an exception makes sense — like when you’re debugging code and trying to isolate a more critical error. 

How Syncro simplifies PowerShell error handling

For nearly 20 years, PowerShell has helped MSPs and IT teams execute, manage, and customize scripts. That means when you’re trying to solve a problem within PowerShell, there’s probably a solution someone else already created. Many of those solutions can be found in the Syncro Community Script Library. 

Syncro’s script library includes 700+ plug-and-play scripts for PowerShell, Batch, VBScript, and Mac Bash. And with Syncro’s scripting engine and breadth of integrations, you can customize error-handling, trigger remediations, and log every action. 

Sign up for a free trial today and explore Syncro’s scripting capabilities.


Bobby Amos, Syncro