zoukankan      html  css  js  c++  java
  • PowerShell: Try...Catch...Finally 实现方法

    PowerShell 本身有很多很好的错误控制,但是习惯于.net编程的人员,更喜欢用Try Catch Finally方法,尤其当有一段代码必须被执行到的时候。现在好了,adweigert 想出了一个好方法来实现。这个函数已经在多种情况下测试过,希望能对你有帮助。

     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 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..."
        }
  • 相关阅读:
    PAIRING WORKFLOW MANAGER 1.0 WITH SHAREPOINT 2013
    Education resources from Microsoft
    upgrade to sql server 2012
    ULSViewer sharepoint 2013 log viewer
    Top 10 Most Valuable Microsoft SharePoint 2010 Books
    讨论 Setsockopt选项
    使用 Alchemy 技术编译 C 语言程序为 Flex 可调用的 SWC
    Nagle's algorithm
    Nagle算法 TCP_NODELAY和TCP_CORK
    Design issues Sending small data segments over TCP with Winsock
  • 原文地址:https://www.cnblogs.com/digjim/p/2558458.html
Copyright © 2011-2022 走看看