Powershell: Try... Catch... Finally Implementation Method

Source: Internet
Author: User

Powershell itself has a lot of good error control, but those who are used to. NET Programming prefer the try catch finally method, especially when a piece of code must be executed. Now, adweigert has come up with a good way to implement it. This function has been tested in many cases and may be helpful to you.

 

1 function try
2 {
3 Param
4 (
5 [scriptblock] $ command = $ (throw "the parameter-command is required ."),
6 [scriptblock] $ catch = {Throw $ _},
7 [scriptblock] $ finally = {}
8)
9
10 &{
11 $ local: erroractionpreference = "silentlycontinue"
12
13 trap
14 {
15 trap
16 {
17 &{
18 trap {Throw $ _}
19 & $ finally
20}
21
22 throw $ _
23}
24
25 $ _ | & {& $ catch}
26}
27
28 & $ command
29}
30
31 &{
32 trap {Throw $ _}
33 & $ finally
34}
35}

 

Example:

 

# Example usage

Try {
Echo ": Do some work ..."
Echo ": Try divide by zero: $(0/0 )"
}-Catch {
Echo ": cannot handle the error (will rethrow): $ _"
# Throw $ _
}-Finally {
Echo ": cleanup resources ..."
}

 

 

 

 

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.