美文网首页
powershell中所有错误和异常处理的方法 判断上一个程序是

powershell中所有错误和异常处理的方法 判断上一个程序是

作者: mudssky | 来源:发表于2021-04-26 15:43 被阅读0次

    01.$LASTEXITCODE$?

    类似于linux的shell脚本,powershell也可以用记录程序退出码的方式判断命令是否执行成功

    其中

    1. $?表示最后一个操作的执行状态。如果最后一个操作成功,则包含 TRUE,失败则包含 FALSE。

    2. $LASTEXITCODE则是返回上一次执行的退出码,因为linux程序通常用退出码0表示执行成功,所以我们判断$LASTEXITCODE是否为0就能判断上次程序执行是否成功。

    总的来说$LASTEXITCODE,逻辑上还要多绕一圈,所以平时方便起见用$?就是了。

    02.trap

    trap关键词可以指定让程序终结的错误发生时,执行一系列语句。

    • trap的默认行为是在执行完statement block里的语句 后显示错误,然后会继续执行脚本或者函数
    • 在trap中使用break可以实现显示错误,然后退出执行
    • 如果想要不显示错误继续执行,可以用continue

    语法

    trap [[<error type>]] {<statement list>}
    

    statement list就是终结错误发生时,会执行的语句。

    错误类型定义了trap的处理范围

    trap处理所有终结错误

    没有类型定义的trap会在所有错误发生的时候执行。

    当一个让程序终结的错误没有找到其他处理的脚本或命令,就会执行trap里面的语句,

    下面是一个例子

    trap {"Error found."}
    
    function TrapTest {
        trap {"Error found."}
        nonsenseString
    }
    
    TrapTest
    

    会出现下面的错误

    Error found.
    nonsenseString:
    Line |
       3 |      nonsenseString
         |      ~~~~~~~~~~~~~~
         | The term 'nonsenseString' is not recognized as the name of a cmdlet,
    function, script file, or operable program. Check the spelling of the name, or
    if a path was included, verify that the path is correct and try again.
    

    trap 中使用$_,也就是powershell自动生成的当前对象,就会被替换成输出的错误

    function TrapTest {
        trap {"Error found: $_"}
        nonsenseString
    }
    
    TrapTest
    
    
    Error found: The term 'nonsenseString' is not recognized as the name of a
    cmdlet, function, script file, or operable program. Check the spelling of the
    name, or if a path was included, verify that the path is correct and try again.
    nonsenseString:
    Line |
       3 |      nonsenseString
         |      ~~~~~~~~~~~~~~
         | The term 'nonsenseString' is not recognized as the name of a cmdlet,
    function, script file, or operable program. Check the spelling of the name, or
    if a path was included, verify that the path is correct and try again.
    

    注意: trap可以在一个作用域代码块(scope)的任何地方定义,即使定义在一个代码块的底部,也会捕获整个代码块的错误

    trap处理特定的错误

    下面是只处理没有找到命令的错误的trap,trap的使用的是.net的异常类型

    trap [System.Management.Automation.CommandNotFoundException]
        {"Command error trapped"}
    

    下面是系统异常类型,System.Management.Automation.CommandNotFoundException是继承自System.Exception的

    trap [System.Exception] {"An error trapped"}
    

    当多个trap同时存在的时候powershell会匹配最精确特定的trap,如下

    trap {"Other terminating error trapped" }
    trap [System.Management.Automation.CommandNotFoundException] {
      "Command error trapped"
    }
    nonsenseString
    
    Command error trapped
    nonsenseString:
    Line |
       5 |  nonsenseString
         |  ~~~~~~~~~~~~~~
         | The term 'nonsenseString' is not recognized as the name of a cmdlet,
    function, script file, or operable program. Check the spelling of the name, or
    if a path was included, verify that the path is correct and try again.
    
    

    trap捕获错误的作用域

    trap捕获错误以后,会执行trap内部的语句,但是错误处后续的代码还会继续执行

    下面是在函数内部发生了错误的情况,错误被内部的trap捕获,并且函数的返回语句被正常执行

    function function1 {
        trap { "An error: " }
        NonsenseString
        "function1 was completed"
    }
    
    function1
    
    An error:
    NonsenseString:
    Line |
       3 |      NonsenseString
         |      ~~~~~~~~~~~~~~
         | The term 'NonsenseString' is not recognized as the name of a cmdlet,
    function, script file, or operable program. Check the spelling of the name, or
    if a path was included, verify that the path is correct and try again.
    function1 was completed
    
    

    下面的例子trap语句被放到函数外面,能够捕获到函数内部的错误,但是函数的返回语句没有被执行

    function function2 {
        NonsenseString
        "function2 was completed"
    }
    
    trap { "An error: " }
    
    function2
    
    An error:
    NonsenseString:
    Line |
       2 |      NonsenseString
         |      ~~~~~~~~~~~~~~
         | The term 'NonsenseString' is not recognized as the name of a cmdlet,
    function, script file, or operable program. Check the spelling of the name, or
    if a path was included, verify that the path is correct and try again.
    

    也就是说,trap如果在函数的外部,就可以实现捕获到错误就停止函数运行的功能。

    注意:多个trap定义相同类型的错误条件的时候,只有最高处定义的trap会被使用

    Remove-Item -ErrorAction Stop ThisFileDoesNotExist
    trap { "whoops 1"; continue }
    trap { "whoops 2"; continue }
    

    注意:trap语句的定义域取决于它编译的位置,如果它在一个函数或者脚本中,那么当函数或脚本退出时,他们内部的trap语句就会被删除

    看下面的例子,函数外的错误没有被函数内的trap捕获

    function function1 {
        trap { "An error: " }
        
        "function1 was completed"
    }
    NonsenseString
    
    function1 was completed
    NonsenseString: C:\Projects\base\test\testexit.ps1:6:1
    Line |
       6 |  NonsenseString
         |  ~~~~~~~~~~~~~~
         | The term 'NonsenseString' is not recognized as a name of a cmdlet, function,
         | script file, or executable program. Check the spelling of the name, or if a
         | path was included, verify that the path is correct and try again.
    

    使用break和continue关键字

    在trap中使用break和continue可以决定终结错误发生时,继续运行还是停止

    默认没有break关键字的情况下是会继续运行的,也会输出错误

    function break_example {
        trap {
            "Error trapped"
            break
        }
        1/$null
        "Function completed."
    }
    
    break_example
    
    Error trapped
    ParentContainsErrorRecordException:
    Line |
       6 |      1/$null
         |      ~~~~~~~
         | Attempted to divide by zero.
    
    

    使用continue语句,powershell将从错误中恢复,并且不会输出错误流

    function continue_example {
        trap {
            "Error trapped"
            continue
        }
        1/$null
        "Function completed."
    }
    
    continue_example
    
    Error trapped
    Function completed.
    

    综上,trap是一种比较简单的广范围的错误处理方式,对于更细粒度的错误处理,建议使用try catch语句

    03.try catch finally

    try 捕获的错误,会被自动保存到$Error变量里面,powershell会寻找catch语句来处理错误。

    这个语法就和c#的异常处理比较像

    语法

    try {<statement list>}`
    catch [[<error type>][',' <error type>]*] {<statement list>}
    finally {<statement list>}
    

    捕获错误

    try { NonsenseString }
    catch { "An error occurred." }
    
    An error occurred.
    

    使用多个catch语句

    try {
       $wc = new-object System.Net.WebClient
       $wc.DownloadFile("http://www.contoso.com/MyDoc.doc","c:\temp\MyDoc.doc")
    }
    catch [System.Net.WebException],[System.IO.IOException] {
        "Unable to download MyDoc.doc from http://www.contoso.com."
    }
    catch {
        "An error occurred that could not be resolved."
    }
    

    在try catch语句中使用trap

    当try语句中包含trap,即使声明了catch语句,也会执行trap,如果trap的位置比try更高,并且没有catch语句,trap也会获得控制,即使父级作用域中包含匹配的catch语句。

    访问错误信息 ACCESSING EXCEPTION INFORMATION

    catch语句中的$_就包含了错误信息

    try { NonsenseString }
    catch {
      Write-Host "An error occurred:"
      Write-Host $_
    }
    
    An Error occurred:
    The term 'NonsenseString' is not recognized as the name of a cmdlet, function,
    script file, or operable program. Check the spelling of the name, or if a path
    was included, verify that the path is correct and try again.
    

    你还可以用$_打印堆栈信息

    try { NonsenseString }
    catch {
      Write-Host "An error occurred:"
      Write-Host $_.ScriptStackTrace
    }
    
    An Error occurred:
    at <ScriptBlock>, <No file>: line 2
    

    使用FINALLY来释放资源

    不管try块是否遇到错误,finally语句都会执行。即使catch中使用exit退出脚本,或者使用ctrl+c中止脚本都会执行。

    相关文章

      网友评论

          本文标题:powershell中所有错误和异常处理的方法 判断上一个程序是

          本文链接:https://www.haomeiwen.com/subject/jajerltx.html