PowerShell error handling, try Catch finally

Source: Internet
Author: User
Tags finally block try catch mailmessage


Script debugging has always been a daunting task, and it was a disaster before PowerShell appeared. Microsoft has finally made a lot of improvements in PowerShell, not only with $error,-whatif, but also with Ise. In addition to the syntax also added try-catch-finally, finally can facilitate debugging and error handling.
In this syntax, finally is not required, but the individual does not recommend that the part be removed. It is recommended that the preprocessing of the feature be placed in the try section, but without errors, and then in the finally completion function.
Here's a piece of code that shows how to do error handling. The main function is to write a string to a new file on the hard disk, and then remove the variable after completion. -noclobber indicates that an existing file is not overwritten.
Try
{
$strContent = "Try Catch Finally"
Out-file-filepath D:\test.txt-InputObject $strContent-noclobber
Write-host "File creation succeeded"
}
Catch [System.UnauthorizedAccessException]
{
Write-host "Access failed. Error reason: "$Error [0]
}
Catch [System.IO.DirectoryNotFoundException]
{
Write-host "Access failed. Error reason: "$Error [0]
}
Catch
{Write-host "Access failed. Error reason: "$Error [0]
}
Finally
{remove-variable strcontent
}
After running in the current script, it runs successfully without any errors. Such as

Run the script again, and the error will be reported. This is exactly what-noclobber has played a role. And we captured the exception through System.IO.DirectoryNotFoundException. In the Catch section, we can proactively capture the errors that can be imagined, which can improve the friendliness of the script, and can proactively handle such errors to improve the usability of the script.

When we change the save location of the output file to a directory that does not exist, we can find the d:\temp\, which is the result of our design.
PowerShell tutorial–try Catch Finally and error handling in PowerShell

One of the key parts's good PowerShell script is error handling. Even in the shortest script, being able to handle errors helps to ensure this an unexpected event would not go on to wreck The system is working on. Take the example below. Every week in We sample company (mycompany.com) Human Resources is going to upload a list telling us who should has ACC ESS to the expenses database. If a name isn ' t in the list from HR we ' re going to remove it from the group and that user would no longer be able to log ex Pense 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. One week HR doesn ' t get around to uploading the list or, just as we're 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-run and, in a very short space of time, it had removed every use R from our expenses group. Pretty soon the irate phone calls start flooding in and life gets a little less happy. The the-the-avoid all-is-to-catch-the-errors and then-handle the event that caused them (which-in-case is halt th E script and has a shout at someone in HR).

Terminating and Non-terminating Errors

One of the key things to know when catching errors are that only certain errors can being caught by default. Errors come in the types–terminating and non-terminating. A terminating error is an error, that would halt a function or operation. If you make a syntax the error or run out of memory, which 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 does you catch a non-terminating error? Basically, you tell PowerShell to treat it as terminating. The ErrorAction parameter. Every PowerShell cmdlet supports ErrorAction. by Specifying-erroraction Stop on the end of a cmdlet to ensure that any errors it throws is treated as terminating and can be caught. In our example above we is going to the change of our get-content line to:

$AuthorizedUsers = get-content \ fileserver\hrshare\userlist.txt-erroraction Stop
Treating all Errors as terminating

It is also possible to treat all errors as terminating using the erroractionpreference variable. You can do this either for the script your is working with or for the whole PowerShell session. To set it into a script, make the first line $ErrorActionPreference = Stop. To set it for the session, type $ErrorActionPreference = Stop at the PowerShell console.

Catching a terminating Error

Once you had ensured that the error you were trying to catch was going to being treated as terminating, you can build a Try Ca TCH block around the command (or commands) that might cause the error. The first stage is to surround, the section of your script, the error with a Try block. In we example the Get-content line becomes:

try{    $AuthorizedUsers = get-content \ fileserver\hrshare\userlist.txt-erroraction Stop}

Immediately after the Try block you must place a Catch block to deal with the error. The Catch block is only accessed if a terminating error occurs, otherwise it is ignored. In our example we is going to email a admin to say that there have been an error and then halt the script. Our get-content:

try{    $AuthorizedUsers = get-content \ fileserver\hrshare\userlist.txt-erroraction stop}catch{    Send-mailmessage-from [email protected]-to [email protected]-subject "HR File Read failed!"-smtpserver EXCH01. AD. mycompany.com Break    }
Accessing the Error Record

Once you be inside a catch block you can access the error record, which was stored in the current object variable, $_. Error Records has various useful properties, but the main one you'll want to access is $_. Exception. Exceptions is really dealing with here as we catch and deal with Errors–exceptions is the unexpected event That caused the error record itself was actually only really a wrapper for presenting the exception to the Powe Rshell user). It is the exception, we are catching, and the exception that contains, the really useful information about the PROBL Em. If there was a further underlying problem this caused our exception, it's also recorded at $_.exception.innerexception (a nd so on–the next underlying exception are stored at $_.exception.innerexception.innerexception etc). For the purposes of our example we is going to use $_. Exception to put some extra information into our notification email, using the $_. Exception.Message and $_. Exception. ItemName Properties:

try{    $AuthorizedUsers = get-content \ fileserver\hrshare\userlist.txt-erroraction stop}catch{    $ ErrorMessage = $_. Exception.Message    $FailedItem = $_. Exception.itemname    send-mailmessage-from [email protected]-to [email protected]-subject "HR File Read failed!"-smt PServer EXCH01. AD. Mycompany.com-body "We failed to read file $FailedItem. The error message was $ErrorMessage ' break    }
Catching specific Exceptions

Now, as our example stands we is catching any errors this occur during the file read and dealing with all of them in T He same. You can however catch specific exceptions and deal with them differently, but–and it ' s a big but–only if the original Error is terminating. Because the Get-content cmdlet throws non-terminating errors (that we had only treated as terminating using erroraction) We cannot specifically catch the different exceptions that the cmdlet might throw. This was a feature of PowerShell and applies to any non-terminating error, regardless of the erroractionpreference and Cann OT be changed. Still, we can deal with other terminating exceptions, such as a out of memory error, which could crop up during the read O Peration. For the purposes of this example, that's what we'll do.

You catch specific terminating errors by specifying the exception name immediately after the Catch keyword. In our example we want to catch a System.outofmemory exception and, if we get one, 'll take the no nonsense approach of R Ebooting the computer immediately. We'll also include a general catch block after our file not found block to catch all other exceptions:

try{    $AuthorizedUsers = get-content \ fileserver\hrshare\userlist.txt-erroraction Stop}catch [ system.outofmemoryexception]{    restart-computer localhost}catch{    $ErrorMessage = $_. Exception.Message    $FailedItem = $_. Exception.itemname    send-mailmessage-from [email protected]-to [email protected]-subject "HR File Read failed!"-smt PServer EXCH01. AD. Mycompany.com-body "We failed to read file $FailedItem. The error message was $ErrorMessage ' break    }
Finally, Using finally

The last part of a Try Catch finally is the finally block. This must is defined immediately after the Catch block and runs every time, regardless of whether there is an error or no T. In the this-you can perform actions, need to is made regardless of whether an operation succeeds or fails. In our example we is going to log the a file read was attempted. Our get-content line now looks like:

try{    $AuthorizedUsers = get-content \ fileserver\hrshare\userlist.txt-erroraction Stop}catch [ system.outofmemoryexception]{    restart-computer localhost}catch{    $ErrorMessage = $_. Exception.Message    $FailedItem = $_. Exception.itemname    send-mailmessage-from [email protected]-to [email protected]-subject "HR File Read failed!"-smt PServer EXCH01. AD. Mycompany.com-body "We failed to read file $FailedItem.  The error message was $ErrorMessage "    break}finally{    $Time =get-date    " This script made a read attempt at $Time " | Out-file C:\logs\ExpensesScript.log-append}


PowerShell error handling, try Catch finally

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.