PowerShell has come a long way since its humble beginnings in 2007. It’s been used to automate many tasks and provide users with an easy-to-use interface for their scripts. When you’re ready to take your skillset to the next level, we’ll show you how Try Catch blocks can help make your code more readable and maintainable.,
PowerShell Try Catch Not Working is a problem that has been present for a while. PowerShell has released 3 fixes to fix the issue. Read more in detail here: powershell try catch not working.
Have you ever launched a script or a PowerShell cmdlet and been greeted with a roaring wall of red text like the one below?
An example of a PowerShell mistake
Errors may be stressful and perplexing. Most importantly, mistakes are often difficult to read, making establishing what and where the script went wrong almost impossible.
Fortunately, PowerShell provides several error handling options to help you out. Errors may be filtered and shown in a manner that makes them simpler to understand using error handling. Understanding the error also makes it simple to add extra logic to the error management process.
In this tutorial, you’ll learn about PowerShell errors and how to intercept them to conduct error handling using the Try Catch blocks in PowerShell (and finally blocks).
Understanding How PowerShell Errors Work
Let’s go over a few principles about mistakes in PowerShell before we go into error management. Understanding mistakes may help you develop more effective error-handling solutions.
The $Error Variable is a built-in variable.
In PowerShell, there are a lot of automatic variables, and one of them is The $Error Variable is a built-in variable.. PowerShell uses the $Error variable to store all errors that are encountered in the session. The $Error variable is an array of errors sorted by most recent.
The $Error variable isn’t set to anything. when you initially start a PowerShell session. You can see whether this is the case by using the $Error variable.
The $Error variable isn’t set to anything.
The $Error variable is initially empty, as you can see. However, once an error is produced, it will be added to the $Error variable and kept there.
The issue is caused in the example below by obtaining a service name that does not exist.
PS> Get-Service xyz PS> $Error PS> $Error.Count
The $Error variable is updated with the error.
The created error was added to the $Error variable, as you can see in the output above.
The $Error variable stores a list of errors that occurred during the PowerShell session. The array location of each mistake may be accessed by calling it. At index 0, the most recent mistake will always be found.
For example, $Error[0] may be used to get the most recent error.
The Properties of the $Error Object
The $Error variable is an object in PowerShell because everything is an object, and objects have attributes. You should get a list of the properties accessible if you pipe the $Error variable to the Get-Member cmdlet.
The Properties of the $Error Object
The content of The InvocationInfo property is used to store information about the invocation. may be viewed using the command below to ascertain the cause of the problem.
The InvocationInfo property is used to store information about the invocation.
You might now repeat the process with the other characteristics to see what else you can learn!
Putting an End to Errors
Putting an End to Errors stop the execution flow when it is encountered by PowerShell vs non-Putting an End to Errors. There are several ways a terminating error can occur. One example is when you call a cmdlet with a parameter that does not exist.
When the command Get-Process notepad runs, the command is valid, and the details of the notepad process are displayed, as shown in the screenshot below.
Details on how to use a notebook
However, when a parameter that does not exist is used, such as Get-Process notepad -handle 251, the cmdlet returns an error stating that the handle parameter is invalid. The cmdlet then terminates without displaying any information about the notepad process.
The argument is incorrect, hence an error is thrown.
Non-Putting an End to Errors
Non-Putting an End to Errors are errors that do not stop the execution of the script or command. For example, check out the code below. This code gets the list of file names from the fileslist.txt file. Then, the script goes through each file name, read the contents of each file, and outputs it on the screen.
foreach ($file in $file list) $file list = Get-Content.filelist.txt $file list = Get-Content.filelist.txt $file list = Get-Content.filelist.txt $ Get-Content $file Write-Output “Reading file $file”
The file names in the list below are the contents of the filelist.txt file.
File 1.log, File 2.log, File 3.log, File 4.log, File 5.log, File 6.log, File 7.log, File 8.log, File 9.log, File 10.log, File 11.log, File 12.log, File 13.log, File 14.log, File 15.log, File 16.log, File 17.log,
But what if File 6.log didn’t exist in the first place? When you execute the code, you can anticipate an error since the script is unable to locate File 6.log. Below is an example of a comparable output.
This is an example of a non-terminating mistake.
The script was able to read the first five files in the list, as you can see in the picture above, but when it attempted to read File 6.txt, it returned an error. Before quitting, the script continues to read the remaining files. It never came to an end.
Variable $ErrorActionPreference
So far, you’ve learned about the terminating and non-Putting an End to Errors and how they differ from each other. But, did you know that a non-terminating error can be forced to be treated as a terminating error?
Preference variables are a notion in PowerShell. These variables may be used to alter PowerShell’s behavior in a variety of ways. $ErrorActionPreference is one of these variables.
Variable $ErrorActionPreference is used to change the way PowerShell treats non-Putting an End to Errors. By default, the $ErrorActionPreference value is set to Continue. Changing the value of Variable $ErrorActionPreference to STOPforces PowerShell to treat all errors as Putting an End to Errors.
To alter the value of $ErrorActionPreference, use the code below.
$ErrorActionPreference = “STOP” $ErrorActionPreference = “STOP”
Visit PowerShell ErrorActionPreference to learn more about additional acceptable $ErrorActionPreference variable values.
Now, refer back to the example used in the Non-Putting an End to Errors section in this article. The script can modified to include the change in $ErrorActionPreference like the code shown below:
# Set the $ErrorActionPreference value to STOP $ErrorActionPreference = “STOP” $ErrorActionPreference = “STOP” foreach ($file in $file list) $file list = Get-Content.filelist.txt $file list = Get-Content.filelist.txt $file list = Get-Content.filelist.txt $ Get-Content $file Write-Output “Reading file $file”
When the $ErrorActionPreference value is set to the default value of Continue, the updated code will act differently than previously.
Forcing a terminating error using Variable $ErrorActionPreference
The script was able to read the first five files in the list, as seen in the picture above, but when it attempted to read File 6.txt, it gave an error since the file was not found. The script then exited, and the remaining files were not read.
Only the current PowerShell session’s $ErrorActionPreference value is valid. When you start a new PowerShell session, it resets to the default setting.
ErrorActionCommon is a parameter in the ErrorAction class.
If the $ErrorActionPreference value is applied to the PowerShell session, the ErrorAction parameter applies to any cmdlet that supports common parameters. The ErrorAction parameter accepts the same values that Variable $ErrorActionPreference does.
The value of the ErrorAction parameter takes priority over the value of the $ErrorActionPreference argument.
Let’s go back to the previous example and utilize the same code. The ErrorAction option is added to the Get-Content line this time.
# Set the value of $ErrorActionPreference to default (CONTINUE) $file list = Get-Content.filelist.txt foreach ($file in $file list) $ErrorActionPreference = “CONTINUE” $file list = Get-Content.filelist.txt foreach ($file in $file list) $ErrorActionPreference = “CONTINUE” $ErrorActionPre # Get-Content $file -ErrorAction STOP -ErrorAction STOP -ErrorAction STOP -ErrorAction STOP -ErrorAction STOP -ErrorAction STOP -ErrorAction STOP -ErrorAction STOP -ErrorAction STOP -Er
Even if the $ErrorActionPreference is set to Continue, the script still terminates when it encounters an error after executing the changed code. Because the PowerShell ErrorAction parameter value in Get-Content is set to STOP, the script ended.
Using the PowerShell ErrorAction argument to force a terminating error
Catch Blocks Using PowerShell
At this point, you’ve learned about PowerShell errors and how Variable $ErrorActionPreference and PowerShell ErrorAction parameters work. Now, it’s time you learn about the good stuff – the PowerShell Try Catch Finally blocks.
Try catch blocks (and the optional finally block) in PowerShell are a means to throw a net around a piece of code and capture any errors that come back.
The Try statement’s syntax is shown in the code below.
try { <statement list> } catch [[<error type>][‘,’ <error type>]*]{ <statement list> } finally { <statement list> }
The Try block contains the code that you want PowerShell to “try” and monitor for errors. If the code in the Try block encounters an error, The $Error variable is updated with the error. and then passed to the Catch block.
The actions to be performed when the Try block returns an error are included in the Catch block. A Try statement may include several Catch blocks.
The code that will be executed at the Conclusion of the Try statement is included in the Finally block. Whether or not an error was counted, this block executes.
Using PowerShell ErrorAction to Catch Non-Specific Errors (Catch-All)
A basic Try statement has two blocks: a Try and a Catch. Finally is an optional block.
For example, to catch a non-specific exception, the Catch parameter should be empty. The example code below is using the same script that was used in the Variable $ErrorActionPreference section but modified to use the Try Catch blocks.
The foreach statement is now included inside the Try block, as seen in the code below. Then, if an error occurs, a Catch block includes the code to show the message An Error Occurred. The code in the Finally section simply clears the variable $Error.
Get-Content.filelist.txt $file list = Get-Content.filelist.txt $file list = Get-Content.file attempt foreach ($file in $file list) Write-Output “Reading file $file” Get-Content $file -ErrorAction STOP Get-Content $file -ErrorAction STOP Get-Content $file -ErrorAction STOP finally $Error.Clear() catch Write-Host “An Error Occurred” -ForegroundColor RED
After executing the code above in PowerShell, you’ll get the result displayed below.
When an error occurred, the script was terminated.
The script met an error, performed the code within the Catch block, and then exited, as seen in the output above.
The mistake was dealt with, which was the goal of error handling in the first place. The error message, on the other hand, was much too broad. You might use the Exception attribute of the error given by the Try block to display a more detailed error.
The code below has been changed, notably the code within the Catch block, to show the exception message from the current error – $PSItem.Exception – that has been sent down the pipeline. Message
Get-Content.filelist.txt $file list = Get-Content.filelist.txt $file list = Get-Content.file attempt foreach ($file in $file list) Write-Output “Reading file $file” Get-Content $file -ErrorAction STOP Get-Content $file -ErrorAction STOP Get-Content $file -ErrorAction STOP finally $Error.Clear() catch Write-Host $PSItem.Exception.Message -ForegroundColor RED
When the above-modified code is executed, the message presented is much more detailed this time.
The script ended with a detailed error notice.
Detecting Particular Errors
There are situations when a catch-all strategy to error handling isn’t the best option. Perhaps you want your script to take a certain action based on the sort of mistake it encounters.
How can you figure out what kind of mistake you’re dealing with? By looking at the TypeName attribute of the last error’s Exception property. Use this command, for example, to discover the error type from the preceding example:
$Error[0]. Get-Member | Exception
The code above would provide the result seen in the image below. As you can see, the TypeName value – System.Management.Automation – is presented. ItemNotFoundException.
Obtaining the TypeName error value
Modify the code to capture the error type you need to intercept now that you know what it is. There are now two Catch blocks, as seen in the changed code below. The first Catch block prevents a certain sort of mistake from occurring (System.Management.Automation.ItemNotFoundException). The second Catch block, on the other hand, includes the general, catch-all error message.
Get-Content.filelist.txt $file list = Get-Content.filelist.txt $file list = Get-Content.file attempt foreach ($file in $file list) Write-Output “Reading file $file” Get-Content $file -ErrorAction STOP Get-Content $file -ErrorAction STOP Get-Content $file -ErrorAction STOP [System.Management.Automation] catch .ItemNotFoundException] -ForegroundColor RED Write-Host “The file $file is not found.” $PSItem.Exception.Message -ForegroundColor RED $PSItem.Exception.Message $PSItem.Exception.Message $PSItem.Exception.Message $PSItem.Exception.Message $PSItem.Exception.Message $PS Finally, $Error.Clear() is called.
The outcome of the updated code is shown in the screenshot below.
The script was terminated with an error message.
Conclusion
In this article, you’ve learned about errors in PowerShell, its properties, and how you can determine an error’s specific type. You’ve also learned the difference between how Variable $ErrorActionPreference and the PowerShell ErrorAction parameter affects how PowerShell treats non-Putting an End to Errors.
You’ve also learned how to handle failures using PowerShell Try Catch Finally blocks, whether for individual faults or as a catch-all technique.
The examples in this article are just meant to highlight the fundamentals of how the Try Catch Finally blocks function. The information you should have received from this article should provide you with the foundation to begin implementing error handling in your scripts.
Additional Reading
The “powershell erroraction” is a command-line tool that allows users to have their script errors handled in various ways. The “erroraction” can be used for try, catch, or finally blocks.
Frequently Asked Questions
How do I use try catch block in PowerShell?
A: In PowerShell, you can use the try catch block to handle exceptions. The syntax is as follows:
try { do something }
catch {}
How do you use catch in PowerShell?
A: The command to watch a file for changes is catch. It can also be used in other commands like the following example, which will compare two text files and print out any differences between them. If a difference exists, it will create an output file with that line of code at the beginning of each changed line.
How do I raise exceptions in PowerShell?
A: To raise exceptions in PowerShell, you need to use the throw keyword. The syntax is as follows:
throw [Exception]
Related Tags
- powershell try catch exception message
- powershell try catch exit
- powershell catch all exceptions
- try catch finally powershell
- powershell try catch continue