From the course: PowerShell for Security Professionals

Create script safeguards through error handling - PowerShell Tutorial

From the course: PowerShell for Security Professionals

Create script safeguards through error handling

Hey, everybody, welcome back to the PowerShell for Security Professionals course. In the last lesson, we covered some basic control flow. We went over for loops, while loops, do while loops, do until loops, and some other things. In this lesson, I wanted to kind of go over error handling and this try catch statement. So, oftentimes, built into a lot of the pre-written commandlets are errors or exceptions that are thrown whenever something behaves not accordingly. There may be scenarios in which we'll want to act on one of those errors. So, for example, if an error is thrown while pinging a certain website or while changing some Active Directory settings, we may want to be notified about this via the command line, or maybe even work with an API to send out a notification or something like PagerDuty or something like that. There's a lot of scenarios in which you'll want to know when your code doesn't work, or when an error is thrown, and the best way to do that is using this try catch block. So, the way that this works is actually pretty simple. You have try, and then you put it at curly brace and inside you write the code that you want to try. And then after that, you write a catch statement. This catch statement will catch any errors. And from here, we can act on those errors. So, in this scenario, in this example, we just want to write the errors through. We just want to write the errors to the PowerShell like console. And so, all this will do is call the write output commandlet, and just let us know that something through an exception and write it to the PowerShell console. If you want to act on it, you can throw in an if statement or whatever. Like if the output equals to something else, then you can change how it behaves. But this is the general structure that we'll write most of our code in, in order to make sure that we're catching any errors that may come from some pre-written commandlet or some code that we write that's not acting the way we want it to act. So yeah, this is a really important tool to have in your PowerShell toolkit. I'd say probably two of the most important videos are this one and the previous one. So, it's really important that you understand control flow. And it's really important that you understand this try catch block and how we use it for error handling. If you understand these two, you can always just use things like ge-help to learn about other commandlets. But knowing how to do handle the control flow and how to deal with errors will become extremely useful not just in this course, but also in your day-to-day job. So yeah, thanks for watching and I'll catch you in the next lesson.

Contents