先看一個指令檔: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。