PowerShell指令碼trap語句捕獲異常寫法執行個體_PowerShell

來源:互聯網
上載者:User

先看一個指令檔:3.three.test.ps1

複製代碼 代碼如下:

Get-FanBingbing #命令不存在

然後這樣捕獲:
複製代碼 代碼如下:

trap [exception]
{
 '在trap中捕獲到指令碼異常'
 $_.Exception.Message
 continue
}
.\3.three.test.ps1

異常捕獲成功,輸出:
複製代碼 代碼如下:
在trap中捕獲到指令碼異常
The term 'Get-FanBingbing' is not recognized as the name of a cmdlet

接下來我把3.three.test.ps1指令檔的內容改成:
複製代碼 代碼如下:
dir D:\ShenMaDoushiFuYun #目錄不存在

再運行,這時沒有捕獲到異常,錯誤為:dir : Cannot find path ‘D:\ShenMaDoushiFuYun' because it does not exist.

於是我想是不是因為終止錯誤與非終止錯誤的區別:所以還寫了try catch捕獲語句,雙管齊下:

複製代碼 代碼如下:

trap [exception]
{
 '在trap中捕獲到指令碼異常'
 $_.Exception.Message
 continue
}
try{
.\3.three.test.ps1
}
catch{
 '在catch中捕獲到指令碼異常'
 $_.Exception.Message
}

異常仍舊:dir : Cannot find path ‘D:\ShenMaDoushiFuYun' because it does not exist.

看來問題不在這裡。事實上是ErrorActionReference的問題,這樣改就OK啦:

複製代碼 代碼如下:

trap [exception]
{
 '在trap中捕獲到指令碼異常'
 $_.Exception.Message
 continue
}
$ErrorActionPreference='stop'
.\3.three.test.ps1

輸出為:
複製代碼 代碼如下:

在trap中捕獲到指令碼異常
Cannot find path 'D:\ShenMaDoushiFuYun' because it does not exist.

簡單分析:
像Get-FanBingbing這樣的異常,是因為命令不存在,確切來講屬於語法錯誤,層級比較高被trap到了。但是像目錄找不到這樣的異常,相對而言層級比較低,預設不能捕獲到,除非顯示指定ErrorAction為stop。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.