paint-brush
How to Stop Your Scripts from Crashing with Try-Catch Magicby@hackercm442rnsd0000357l5by3msvv
New Story

How to Stop Your Scripts from Crashing with Try-Catch Magic

by December 17th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

An error in a PowerShell script will prevent it from completing script execution successfully. Using error handling with try-catch blocks allows you to manage and respond to these terminating errors. Handling errors effectively in scripts can save a lot of troubleshooting time and provide better user experiences.
featured image - How to Stop Your Scripts from Crashing with Try-Catch Magic
undefined HackerNoon profile picture

Errors in a PowerShell script can prevent successful execution. Implementing try-catch blocks enables error management and response. This post covers try/catch basics and how to handle custom error messages in PowerShell. Effective error handling saves troubleshooting time and improves user experience. PowerShell offers robust options for exception management with try, catch, and finally blocks. Learn to use try-catch for graceful error handling and to add custom error messages for enhanced feedback.

Why Use Exception Handling in PowerShell?

Scripts can fail for many reasons: missing files, invalid input, or network issues, to name a few. With exception handling, you can capture these issues, inform users in a friendly way, and potentially recover from errors without crashing your script. Using try-catch, you can:


  • Catch specific errors.
  • Display user-friendly messages.
  • Log errors for debugging.

Syntax overview of Try/Catch

Like similar in other programming languages, the try-catch block syntax is very simple and syntax will be the same. It is framed with two sections enclosed in curly brackets (the first block is a try and the second is the catch block).


try { 

#Functionality within try block 

} 

catch 

{ 

#Action to do with errors 

}


The main purpose of using the try-catch block, we can start to manipulate the error output and make it more friendly for the user.

Example 1:

After executing the below script, the below error will be shown on the screen as output and it would occupy some space and the problem may not be immediately visible to the User. So you can use a try-catch block to manipulate the error output and make it more friendly.

without Try-Catch block


Get-content -Path “C:\dotnet-helpers\BLOG\TestFiled.txt”


with Try Catch block

In the below script, we added the ErrorAction parameter with a value of Stop to the command. Not all errors are considered “terminating”, so sometimes we need to add this bit of code in order to properly terminate into the catch block.


try {

Get-content -Path “C:\dotnet-helpers\BLOG\TestFile.txt” -ErrorAction Stop

}

catch { 

Write-Warning -Message “Can’t read the file, seem there is an issue”

}


Example 2:

Using the $Error Variable

To improve the code and follow best practices, consider the following improvements:


  1. Use More Descriptive Error Messages: When handling errors, it's useful to log or display meaningful error messages rather than generic ones. If you mention a custom message, ensure it provides useful information to the user.
  2. Avoid Hardcoding Indexes: Instead of hardcoding the index to access $Error[0], consider using .First() for better readability and understanding of what exactly you're accessing (especially in PowerShell).


Here's a refined version of how you might handle errors using $Error:

try{
 
Get-content -Path "G:\dotnet-helpers\BLOG\TestFiled.txt" -ErrorAction Stop
}
# It will execute if a specific file is not found in a specific Directory
Catch [System.IO.DirectoryNotFoundException] {
 
Write-Warning -Message "Can't read the file, seems there is an issue"
Write-Warning $Error[0]
}
# It will execute if the specified driver is not found in the specified path
Catch [System.Management.Automation.DriveNotFoundException]{
Write-Warning -Message "Custom Message: Specific driver is not found"
Write-Warning $Error[0]
 
}
#Execute for Un-Handled exception - This catch block will run if the error does not match any other catch block exception.
Catch{
Write-Warning -Message "Oops, An un-expected Error Occurred"
#It will return the exception message for the last error that occurred.
Write-host $Error[0].Exception.GetType().FullName
}