Error handling in PowerShell and explore the powerful `try`/`catch`/`finally` blocks.

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everybody today we're going to check out Powershell error handling because you will get Powershell errors in fact you probably already have had Powershell errors we're going to check out how Powershell actually works with those errors what we can do to better analyze them and also what we can do to handle those errors in our code with try catch finally blocks so we can produce outputs that make sense to our users and outputs that make sense to us and be able to see exactly how to continue with our code should we start to get terminating or non-terminating errors so without further Ado let's get straight into error handling within Powershell and try catch file new blocks within Powershell [Music] okay so here I am inside my vs code environment and I'm going to produce an error in fact I'm going to produce the simplest error I can think of which is this one over zero or more to the point we are doing a divide by zero now that's going to cause all sorts of interesting problems but if I go and press F5 on my keyboard and run this you'll see I get an error called attempted to divide by zero in red very good now this error is actually stored within Powershell there is a default variable in fact there are a number of default variables in Powershell but there is a default Powershell error variable called dollar error now if I look inside my shell here and I run that dollar error variable you'll notice the output here is that same error it's no longer actually colored in red but it's actually the same error that we just got we can produce a couple more errors so say for example if I did an error like get Dash service and get service name and I get service name of Apple now I don't have a service called Apple if I highlight that code and press f8 to run it what you will see is I cannot find any service with name Apple so I've now had two errors I've had the error for divide by zero and the error four a service not existing now these have both actually gone into that dollar error variable down here and the thing about this dollar error variable is this dollar error variable is not just going to contain a single error it's going to contain every error that's happened in this current session so if we look at my terminal now notice I've actually got this divide by zero error and I've also got this other error called cannot find any service name in Apple so what that means is if you remember back to us talking about arrays we can go and select the first element in this array if we choose error dollar error and then use square brackets zero and run this you will always get the most recent error that has actually been returned if I go and have a look at Error 1 that is the previous error of divide by zero so this is actually a stack of Errors that's coming in so any errors that we actually get inside our code are always going to be passed to this error variable that we can check out and output later on should we want to so what I can also do here is I can count the amount of Errors I've recently had I could even use dollar error dot count here so dollar error dot count and go and run that code and you can see I've got three errors that are actually inside here now you can also clear these things down as well so we can do dollar error Dot clear and do that with two brackets we've now cleared out our dollar error variable and we can go and have a look at Dollar error again and you'll notice I've got no errors actually included inside there so what happens if I want to handle these errors because if we go and run divide by zero again for example one over zero we might not want to see something like this we might want to see something a little more sensical the same thing with this get service if we got if I go and run this get service again notice it does say get service cannot find any service with name Apple the problem that I find with Powershell is that when people and especially it people that are not experienced with scripting see Powershell errors they see this big block of red and their eyes just glaze over they just ignore it it's just like oh error broken it doesn't work people don't tend to read what is in front of their face so we can see here this does say cannot find any service with the name Apple it does kind of make sense to us but we might want to make that look a little bit different we might want to change the output of this error now we can kind of do that by catching the error and then deciding what we're actually going to do with it so let's go check out something called a try catch finally statement so this is something called a try catch finally Block it's a concept that you find in a lot of different programming languages essentially you want to take those errors and handle them in very specific ways so in this case we have our code written in three different components a try a cat and a finely blocked down here so a try catch or try block here is where we run our actual code this could be in this case divide by zero or this could be the code that I had previously which was get service name Apple it could be something extremely complicated it could be a collection of functions it could be a massive block of code down here it doesn't actually particularly matter but what we want to do is we want to actually go and catch this error itself so by using this catch block this is going to catch any error outputs and display this instead so in this case we're going to write host an error has occurred now we could change this around a bit so for example I could do something like foreground color and we could do something like cyan down here and we could do background color and do something like white by doing this our error is going to look very different to what it normally does in red and it's going to mean that people are more likely to actually read what's on the screen our finely block will actually always run so sometimes we can run some code that is not actually going to produce an error and then the final block will still run after this so for example let's go and comment out this code for a moment and let's go run some code that actually will work so let's do five plus seven and we're going to run that code right now and we can see that try block has completed five plus seven and the output for that is 12 and the finely block as initiated we would initiated this option that just says write host clean up now the central piece here this catch block hasn't run but if we go and produce something that does make an error like for example that one slash zero run exactly the same code look I've got an error has occurred because it's written my error has occurred with a foreground color of cyan and a background color of white so this might actually get people to look at it a bit more maybe we change the background color to Yellow go and run that again and now we've got an even other looking block of text down there that people are more likely to actually read let's have a look at a little bit more of a complex example here we've got another try Catch family block but what you'll see here is first of all I don't actually have the finally you don't need the finally it's completely optional inside here I do inside my try block though here I have a function that I've written called get directory count very very basic function all this is actually going to do is going to get a directory that you actually pass as a parameter and it's going to count the amount of directories in that directory the amount of folders in that directory and output that for us but then going to call that function down here and call it with the directory of C column and see what we've got so if I run that I should get an output it says there are seven folders within this folder because it has run successfully let's go and change that directory output not to C let's change that to X and that is not an x on this computer now if I go and run this I'm actually going to get two elements in this cache the first one is actually my right host here directory does not exist and then the other one is write host dollar underscore.exception Dot message foreground color head now if you put a dollar underscore or a dollar PS item it doesn't matter which one both of those mean exactly the same thing into your catch block this is actually going to reference the error variable this is going to reference actually what has passed out of this try block down here and I'm going to look at the exception.message so just the message component of that error to try and simplify things a little for us so if we go and run this now you can see I've actually got both of those outputs a directory does not exist and I've also got a parameter cannot be found that matches the parameter name directory and it doesn't have the extra components around that error so it having one error and just one line people are much more likely to read that error and actually make sense of that error rather than just have their eyes glaze over and not read what's in front of the screen [Music] so here we have another example on our try catches and in this example we have a system.net web client which is actually going to attempt to download a file but what we're going to do is instead of catching every single error we are going to catch a very specific error these are net exceptions if our commandlet here within the try block actually throws a.net exception within system.net web exception or system.io.io exception it will write out that final that finally clutch sorry it will write out that catch block on the other hand if it doesn't match this specific thing it will actually write out a generic error down the bottom here an error occurred that cannot be resolved I'm sure we've already had errors come up that says an unknown error has occurred the reason why an unknown error has occurred is because the programmer has not put error handling in for that specific type of error and is attempting to throw and generic error now interestingly if we go and run this now you'll notice that the output I actually get is unable to download my.doc from contoso.com because we have not matched this specific error output for system.net web exception we can also actually throw our own errors very quickly and easily in Powershell too we can actually do that just with the throw command if we throw fail or actually we will throw failure what actually comes back here is an error that contains that word failure so this actually logs as an error but we have manually thrown it ourselves what that means is we can have multiple catch statements for the same try block so clear that down let's check out this try catch 4. look at this block of code slightly different zoom in a little bit to it what we have is we have a catch block here on a try block at the top so dollar a is equal to one and we're going to try if dollar a is equal to one throw one well it is equal to one so it's going to throw an error for us automatically and that error is just going to contain one that's all so just look again if I run only that line we have throw one is actually throwing an error of one that's the output our catch is going to catch this so if we're catching with an if Block in here if the error remember the pipeline contains the error contains exception.message is equal to one then throw error one else just throw the message itself let's go run that code and now we notice we've got error one so we have caught our own specific errors now what about if we change this around let's do if dollar a is equal to one throw one and let's do something else let's do else if and let's do dollar a is equal to two then we'll run an elsif thing in here and we'll do another throw let's take this Auto predicted comments out let's throw two and now if I go and grab this catch block down here we change this around so if the dollar exception error message equal to one through error one else throw an exception message maybe what we want to do here is Drop In Like A Catch just for that we can just drop a catch Block in here and put another else if else if that dollar exception message is not equal to one but that dot X exception message is equal to two we want to throw or we want to print error two I'm going to run that in this sense we can see we've got error one if I go and change a to two on here I'm gonna run that same code again we should get error 2 on the output so what we're doing here is we're actually handling two different types of Errors now if we're handling many many errors we might not want to use if statements we might want to actually use switch cases instead as that would be more efficient than churning through lots and lots of else else ifs down there to find the right error we could also still include a finally block on that if we really want to so we can do finally just write a funny Block in the end right dash host code is done do a little foreground color of cyan on there and go and run that process there we go code is done and we have error two so this is a very brief overview of error handling within Powershell now there is one more thing to cover here and these are error types or more to the point terminating errors [Music] okay so we're going to top this off by looking at a final component here we're going to look at different error types so let's check out this try catch finally block it looks very simple we have a single thing here that says get content non-existent file but once that errors out because non-existent file doesn't exist catch and write computer says no and then also put a finally block on the end that says write host completed now let's go run that and see what happens we should catch the error or not now notice the error here is actually displaying as normal it's not being caught by the catch block why is that because of the type of error that we've actually got down here now if we go and look at the error action types we've actually got a number of different error action types here within Powershell we've got things like silently continue this value causes Powershell to suppress all error messages and continue with the script execution we've got stop errors this value causes Powershell to treat non-terminating errors as terminating errors a stop error that's the kind of error that the catch block cap watches if it's if it's in Para it won't catch it continue this value is the default setting displays the error message to the console but the script execution continues and inquire the value prompts the user to choose whether to continue or stop or suspend this value behave similar to inquire but instead of prompting the user it suspends the execution and waits for user input so if I go back to my error action over here what I actually want to do is I want to change this get content over here to have honest a new error action if I put Dash error action on the end I have the ability here to choose whether I can continue ignore inquire silently continue stop or suspend so if I change this error output type to stop and go and run the code again now you should be able to see computer says no wonderful but what about if I don't want to do that for every single command I run because this is a parameter on that command also if this is a badly written command look you might not find that parameter available to you to change the error action type you can change this in a global variable if you really want to Across the entire script so instead of putting an error action type stop there what I could actually do within this Triad block is to find a new variable called error action preference now it has to be called error action preference and notice the color has changed slightly differently to a normal variable inside my vs code and I'm going to put the error action preference as stop that will do the same thing but it will set every single error that outputs within this block of code to a stop so if I go and run that now we've still got computer says no if I change this error action preference to continue and run that again you'll find that that error is actually displayed because the catch block isn't being engaged so remember the catch blocks only actually engage if they catch a stop error not a continue or silently continue error down here and that kind of completes this component for looking at a little bit about Powershell errors and try catch finally blocks I hope you'll find this useful in your own code and I hope you'll join me next time for more on learning Powershell [Music] and you know the routine hashtag like And subscribe and I hope you enjoyed this video and will join me next time goodbye [Music] foreign
Info
Channel: Mike in the Cloud
Views: 2,961
Rating: undefined out of 5
Keywords: PowerShell, error handling, try catch finally, scripting, PowerShell scripting, PowerShell tutorials, scripting tutorials, exception handling, error management
Id: qraTZZOiHVc
Channel Id: undefined
Length: 18min 17sec (1097 seconds)
Published: Mon Jun 19 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.