powershell腳本trap語句捕獲異常寫法實例

字號:


    這篇文章主要介紹了powershell腳本trap語句捕獲異常寫法實例,包含幾個代碼實例,需要的朋友可以參考。
    先看一個腳本文件:3.three.test.ps1
    代碼如下:
    get-fanbingbing#命令不存在
    然后這樣捕獲:
    代碼如下:
    trap[exception]
    {
    '在trap中捕獲到腳本異常'
    $_.exception.message
    continue
    }
    .\3.three.test.ps1
    異常捕獲成功,輸出:
    代碼如下:
    在trap中捕獲到腳本異常
    theterm'get-fanbingbing'isnotrecognizedasthenameofacmdlet
    接下來我把3.three.test.ps1腳本文件的內(nèi)容改成:
    代碼如下:
    dird:\shenmadoushifuyun#目錄不存在
    再運行,這時沒有捕獲到異常,錯誤為:dir:cannotfindpath‘d:\shenmadoushifuyun'becauseitdoesnotexist.
    于是我想是不是因為終止錯誤與非終止錯誤的區(qū)別:所以還寫了trycatch捕獲語句,雙管齊下:
    代碼如下:
    trap[exception]
    {
    '在trap中捕獲到腳本異常'
    $_.exception.message
    continue
    }
    try{
    .\3.three.test.ps1
    }
    catch{
    '在catch中捕獲到腳本異常'
    $_.exception.message
    }
    異常仍舊:dir:cannotfindpath‘d:\shenmadoushifuyun'becauseitdoesnotexist.
    看來問題不在這里。事實上是erroractionreference的問題,這樣改就ok啦:
    代碼如下:
    trap[exception]
    {
    '在trap中捕獲到腳本異常'
    $_.exception.message
    continue
    }
    $erroractionpreference='stop'
    .\3.three.test.ps1
    輸出為:
    代碼如下:
    在trap中捕獲到腳本異常
    cannotfindpath'd:\shenmadoushifuyun'becauseitdoesnotexist.
    簡單分析:
    像get-fanbingbing這樣的異常,是因為命令不存在,確切來講屬于語法錯誤,級別比較高被trap到了。但是像目錄找不到這樣的異常,相對而言級別比較低,默認(rèn)不能捕獲到,除非顯示指定erroraction為stop。