Home » How to Use Try Catch Finally in PowerShell

How to Use Try Catch Finally in PowerShell

PowerShell error handling capabilities enable you to manage and respond to terminating errors in your script effectively. The effective error handling is essential for writing robust and reliable scripts.

The try, catch and finally blocks provides a structured approach to error handling in PowerShell, enabling you to handle errors and ensure your scripts remain robust and reliable.

Understanding Try-Catch-Finally Blocks in PowerShell

In PowerShell, error handling is accomplished using the try, catch, and finally blocks. Each block serves a specific purpose.

  • Try block: This block contains the PowerShell code that you want to monitor for errors. PowerShell executes the code within the try block and if an error occurs, it immediately jumps to the catch block.
  • Catch block: This block is responsible for handling the errors that occur in the try block. You can have multiple catch block to handle different types of errors.
  • Finally block: This block is optional and contains the code that executes regardless of whether an error occurred in the try block. It’s useful for cleaning up resources or performing any necessary actions.

Syntax of Try Catch Finally in PowerShell

The basic syntax for using the try-catch-finally block in PowerShell is as follows:

try {
    # Code that may cause an error
}
catch {
    # Code to handle the error
}
finally {
    # Code that will run regardless of an error
}

Try-Catch-Finally Block in PowerShell

Let’s understand using the try-catch-finally block in PowerShell with example. In the following example, script contains the try-catch and finally block. The try and catch block always exists, finally block is optional.

try
{
    # Code that may generate errors
    $result = 5/0
}
catch
{
    # catch and handle error
    Write-Host "An error occurred."
}
finally
{
    # code that will run regardless of an error
    Write-Host "Finally block execution in progress..."
}

Result:

An error occurred.
Finally block execution in progress...

In the try block, it contains the code that may generates an error, in our case, it is divide by 0 exception.

The catch block catch and handle an error and print the message on the terminal. The finally block is optional and always run regardless of whether an error occurred in the try block.

How to Handle File not Found Error using Try-Catch Block in PowerShell

In PowerShell, file operations are a common task in many scripts. One frequent scenarios involves reading file contents.

In the following example, a try block attempts to read the contents of a file. If the file is not found at the specified path, an error is thrown, which is then caught by the catch block.

try {

    $filePath = "C:\temp\1.txt"

    $fileContents = Get-Content -Path $filePath -ErrorAction Stop

    Write-Host "File contents:" $fileContents

}
catch {
    Write-Host "An error occurred while reading the file: $($_.Exception.Message)"
}
finally {
    # Clean up or finalize
}

In the above example, the try-block attempts to read the contents of the file located at $filePath. The -ErrorAction Stop parameter ensures that if an error occurs, it is treated as terminating error, causing the catch block to be executed.

The error message is then accessed through $_ representing the current execution object, and displayed using Write-Host cmdlet in PowerShell.

Best Practices for Error Handling in PowerShell

To handle errors effectively in PowerShell, follow the given below best practices.

  1. Use Terminating Errors: By default, many PowerShell cmdlets generates non-terminating errors, which don’t stop script execution. To handle these errors, use the -ErrorAction Stop parameter or set the $ErrorActionPreference variable to “Stop
  2. Use Specific Error Types: When catching errors, use specific error types instead of the generic [Exception] type. This allows you to handle different errors with specific response.
  3. Resource Cleanup : Use the finally block for resource cleanup, such as closing file handles, db connections etc..
  4. Logging: Log error information to provide help in troubleshooting and debugging script issues.

Conclusion

I hope the above article on how to handle error using the try-catch-finally block in PowerShell is useful to you.

PowerShell try, catch and finally blocks provides a structured approach to error handling, manage unexpected scenarios and ensure script stability.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.