先看一個腳本文件: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。
您可能感興趣的文章:- Stream、WshShell、WshUrlShortcut對象及Shell.Application的參數與使用
- PowerShell: Try...Catch...Finally 實現方法
- PowerShell中使用Out-String命令把對象轉換成字符串輸出的例子
- PowerShell小技巧之True和False的類型轉換
- shell實現tr刪除替換詳解