Error Handling In Powershell V2
Contents |
Keith BabinecJune 9, 201320 0 0 0 Today’s post (and this blog's inaugural post!) is An Introduction to Error Handling in PowerShell. We will discuss error types, the $error variable, error action error handling powershell try catch preferences, try/catch blocks, and $lastexitcode. The first requirement is to understand the types error handling in powershell example of errors that can occur during execution. Terminating vs. Non-Terminating Errors: Terminating Error: A serious error during execution that halts the error handling in powershell script command (or script execution) completely. Examples can include non-existent cmdlets, syntax errors that would prevent a cmdlet from running, or other fatal errors. Non-Terminating Error: A non-serious error that allows execution to continue
Powershell Error Handling Best Practices
despite the failure. Examples include operational errors such file not found, permissions problems, etc. Update 12/13/2013: Writing a cmdlet? For further information regarding how a cmdlet should determine when to throw a terminating error or non-terminating error, MSDN has a niceexplanationhere. Update 12/13/2013: Want to know if an error you encountered is terminating or non-terminating? Check to see ifthe error behavioris affected by changing the$ErrorActionPreference. According to powershell error handling function the MSDN documentation here, "Neither $ErrorActionPreference nor the ErrorAction common parameter affect how Windows PowerShell responds to terminating errors (those that stop cmdlet processing).". The $error variable: When either type of error occurs during execution, it is logged to a global variable called $error. This variable is a collection of PowerShell Error Objects with the most recent error at index 0. On a freshly initialized PowerShell instance (no errors have occurred yet) the $error variable is ready and waiting as an empty collection: PS C:\> $error.GetType() IsPublic IsSerial NameBaseType ----- ----- -------- TrueTrueArrayListSystem.Object PS C:\> $error.Count 0 In the next snippet I have executed a cmdlet that doesn’t exist, throwing an error. If we grab the count on $error, you will notice it has increased to one item. Dumping that object to the pipeline by accessing $error[0] just prints the error we already saw, right back at us. PS C:\> ThisCmdlet-DoesNotExist The term ‘ThisCmdlet-DoesNotExist' is not recognized as the name of a cmdlet, f unction, script file, or operable program. Check the spelling of the name, or i f a path was included, verify that the path is correct and try again. At line:1 char:24 + ThisCmdlet-Doe
being able to handle errors helps to ensure that an unexpected event will not go on to wreck the system you are working on. Take the example below. Every week in our sample company (MyCompany.Com) Human Resources are going powershell error handling silentlycontinue to upload a list telling us who should have access to the Expenses database. If
Powershell Error Handling Copy-item
a name isn’t in the list from HR we’re going to remove it from the group and that user will no longer be
Powershell Error Handling The Rpc Server Is Unavailable
able to log expense claims: $AuthorizedUsers= Get-Content \\ FileServer\HRShare\UserList.txt $CurrentUsers=Get-ADGroupMember "Expenses Claimants" Foreach($User in $CurrentUsers) { If($AuthorizedUsers -notcontains $User) { Remove-ADGroupMember -Identity "Expenses Claimants" -User $User } } Now, you can see where this is going to go wrong. https://blogs.msdn.microsoft.com/kebab/2013/06/09/an-introduction-to-error-handling-in-powershell/ One week HR doesn’t get around to uploading the list or, just as we are about to access the list, the file server dies. Suddenly PowerShell throws an error on the Get-Content cmdlet and the $AuthorizedUser variable remains empty. Because our script doesn’t handle errors, it continues to run and, in a very short space of time, it has removed every user from our expenses group. Pretty soon the irate phone calls start flooding in and life http://www.vexasoft.com/blogs/powershell/7255220-powershell-tutorial-try-catch-finally-and-error-handling-in-powershell gets a little less happy. The way to avoid all this is to catch the errors and then handle the event that caused them (which in this case is halt the script and have a shout at someone in HR). Terminating and Non-Terminating Errors One of the key things to know when catching errors is that only certain errors can be caught by default. Errors come in two types – terminating and non-terminating. A terminating error is an error that will halt a function or operation. If you make a syntax error or run out of memory, that is a terminating error. Terminating errors can be caught and handled. Non-terminating errors allow Powershell to continue and usually come from cmdlets or other managed situations. Under normal circumstances they cannot be caught by Try-Catch-Finally. The Get-Content error in the example above is a non-terminating error. Treating Non-Terminating Errors as Terminating So how do you catch a Non-Terminating error? Basically, you tell PowerShell to treat it as terminating. To do this you use the ErrorAction parameter. Every PowerShell cmdlet supports ErrorAction. By specifying -ErrorAction Stop on the end of a cmdlet you ensure that any errors it throws are treated as terminating and can be caught. In our example above we are going to change our Get-Content line to: $AuthorizedUsers= Get-Content \\ FileServer\HRShare\UserList.txt -ErrorAction Stop Treating All Errors as Terminating I
August 3, 2009 by rkeithhill There are several facets to the subject of errors in PowerShell that you should understand to get the most out of PowerShell. Some of these facets are error https://rkeithhill.wordpress.com/2009/08/03/effective-powershell-item-16-dealing-with-errors/ handling, error related global variables and error related preference variables. But the most fundamental facet is the distinction between “terminating” and “non-terminating” errors. Terminating Errors Terminating errors will be immediately familiar to software http://stevenmurawski.com/powershell/2009/07/deep-dive-error-handling-error-types-part-1/ developers who deal with exceptions. If an exception is not handled it will cause the program to crash. Similarly if a terminating error is not handled it will cause the current operation error handling (cmdlet or script) to abort with an error. Terminating errors and are generated by: Cmdlet calling the ThrowTerminatingError API. Exceptions escaping unhandled from a cmdlet Script using the “throw” keyword to issue a terminating error Script syntax errors The gist of a terminating error is that the code throwing the terminating error is indicating that it cannot reasonably continue and is aborting the requested powershell error handling operation. As we will see later, you as the client of that code, have the ability to declare that you can handle the error and continue executing subsequent commands. Terminating errors that are not handled propagate up through the calling code, prematurely terminating each calling function or script until either the error is handled or the original invoking operation is terminated. Here is an example of how a terminating error alters control flow: PS> "Before"; throw "Oops!"; "After"BeforeOops!At line:1 char:16+ "Before"; throw <<<< "Oops!"; "After" + CategoryInfo : OperationStopped: (Oops!:String) [], RuntimeException + FullyQualifiedErrorId : Oops! Note that “After” is not output to the console because “throw” issues a terminating error. Non-terminating Errors Have you ever experienced the following in older versions of Windows Explorer? You open a directory with a large number of files, say your temp dir, and you want to empty it. You select the entire contents of the directory, press Delete and wait. Unfortunately some processes invariably have files open in the temp directory. So after deleting a few files, you get an error from Windows Explorer indicating that it can’t delete some file. You press OK an
PowerShell has two kinds of errors – terminating errors and non-terminating errors. Terminating errors are the errors that can stop command execution cold. Non-terminating errors provided an additional challenge, as you need to be notified of failed operations and continue with pipeline operations. To deal with this issue and to provide additional output options, PowerShell employs the concept of streams. There are three additional streams (other than the primary pipeline stream) available in PowerShell – Verbose, Warning, and Error (and . We’ll be concerning ourselves with the output from the Error stream. There are some automatic variables in the shell that deal with errors as well. $ErrorActionPreference is a variable that describes how PowerShell will treat non-terminating errors. $ErrorActionPreference has four options: “Continue” (the default), “SilentlyContinue”, “Inquire”, and “Stop”. $error is an array of all the errors that have occurred in the current session up to the number specified in $MaximumErrorCount. $? is a boolean value that is $true if the previous operation succeeded and $false if it did not. PowerShell does have some built in flexibility to turn non-terminating errors into terminating errors. Based on our setting of $ErrorActionPreference, PowerShell will treat a non-terminating error differently. If $ErrorActionPreference is set to '”Stop”, PowerShell will treat the errors from that scope and all sub scopes (unless explicitly overridden) as terminating errors. If “Inquire” is chosen as the $ErrorActionPreference, then PowerShell will prompt the user at the console upon each error to ask whether it should continue (treat as non-terminating) or halt (treat as terminating), as well as providing an option to drop into a nested prompt. $ErrorActionPreference is a global preference that can be set, but the PowerShell runtime also allows more granular control by providing common parameters for -ErrorAction and -ErrorVariable (shorthand -EA and –EV) which allow you to determine per cmdlet (and in V