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.
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:
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.
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.
Get-content -Path “C:\dotnet-helpers\BLOG\TestFiled.txt”
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”
}
To improve the code and follow best practices, consider the following improvements:
$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
}