先看一個(gè)腳本文件:3.three.test.ps1
復(fù)制代碼 代碼如下:
Get-FanBingbing #命令不存在
然后這樣捕獲:
復(fù)制代碼 代碼如下:
trap [exception]
{
'在trap中捕獲到腳本異常'
$_.Exception.Message
continue
}
.\3.three.test.ps1
異常捕獲成功,輸出:
復(fù)制代碼 代碼如下:
在trap中捕獲到腳本異常
The term 'Get-FanBingbing' is not recognized as the name of a cmdlet
接下來(lái)我把3.three.test.ps1腳本文件的內(nèi)容改成:
復(fù)制代碼 代碼如下:
dir D:\ShenMaDoushiFuYun #目錄不存在
再運(yùn)行,這時(shí)沒(méi)有捕獲到異常,錯(cuò)誤為:dir : Cannot find path ‘D:\ShenMaDoushiFuYun' because it does not exist.
于是我想是不是因?yàn)榻K止錯(cuò)誤與非終止錯(cuò)誤的區(qū)別:所以還寫(xiě)了try catch捕獲語(yǔ)句,雙管齊下:
復(fù)制代碼 代碼如下:
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.
看來(lái)問(wèn)題不在這里。事實(shí)上是ErrorActionReference的問(wèn)題,這樣改就OK啦:
復(fù)制代碼 代碼如下:
trap [exception]
{
'在trap中捕獲到腳本異常'
$_.Exception.Message
continue
}
$ErrorActionPreference='stop'
.\3.three.test.ps1
輸出為:
復(fù)制代碼 代碼如下:
在trap中捕獲到腳本異常
Cannot find path 'D:\ShenMaDoushiFuYun' because it does not exist.
簡(jiǎn)單分析:
像Get-FanBingbing這樣的異常,是因?yàn)槊畈淮嬖冢_切來(lái)講屬于語(yǔ)法錯(cuò)誤,級(jí)別比較高被trap到了。但是像目錄找不到這樣的異常,相對(duì)而言級(jí)別比較低,默認(rèn)不能捕獲到,除非顯示指定ErrorAction為stop。
您可能感興趣的文章:- 收集的48個(gè)Shell腳本小技巧
- Shell腳本echo指令使用小技巧
- Shell腳本計(jì)算字符串長(zhǎng)度和判斷字符串為空小技巧
- 寫(xiě)出健壯Bash Shell腳本的一些技巧總結(jié)
- PowerShell腳本性能優(yōu)化技巧總結(jié)
- Powershell小技巧之查找腳本中的函數(shù)
- Powershell小技巧之記錄腳本的操作
- Powershell小技巧之找出腳本中的錯(cuò)誤
- 十三個(gè)寫(xiě)好shell腳本的技巧分享