Powershell小技巧之捕獲腳本內(nèi)部的異常
先看一個腳本文件: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腳本文件的內(nèi)容改成:
dir D:\ShenMaDoushiFuYun #目錄不存在
再運行,這時沒有捕獲到異常,錯誤為:dir : Cannot find path ‘D:\ShenMaDoushiFuYun' because it does not exist.
于是我想是不是因為終止錯誤與非終止錯誤的區(qū)別:所以還寫了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到了。但是像目錄找不到這樣的異常,相對而言級別比較低,默認(rèn)不能捕獲到,除非顯示指定ErrorAction為stop。
相關(guān)文章
PowerShell函數(shù)中把參數(shù)傳入另一個函數(shù)的函數(shù)傳參例子
這篇文章主要介紹了PowerShell函數(shù)中把參數(shù)傳入另一個函數(shù)例子也是使用的PSBoundParameters,但是有區(qū)別哦,,需要的朋友可以參考下2014-07-07PowerShell Out-File向只讀文件寫入內(nèi)容的方法
這篇文章主要介紹了PowerShell Out-File向只讀文件寫入內(nèi)容的方法,只需要加一個-Force參數(shù)即可,需要的朋友可以參考下2014-08-08windows Powershell 快速編輯模式和標(biāo)準(zhǔn)模式
powershell控制臺有兩種模式,一個是快速編輯模式,一個是標(biāo)準(zhǔn)模式。2014-08-08PowerShell中的強(qiáng)類型數(shù)組介紹
這篇文章主要介紹了PowerShell中的強(qiáng)類型數(shù)組介紹,強(qiáng)類型數(shù)組可以理解為強(qiáng)制數(shù)據(jù)類型的數(shù)組,也就是一個數(shù)組里只包含一種數(shù)據(jù)類型,需要的朋友可以參考下2014-08-08PowerShell中使用Out-String命令把對象轉(zhuǎn)換成字符串輸出的例子
這篇文章主要介紹了PowerShell中使用Out-String命令把對象轉(zhuǎn)換成字符串輸出的例子,即把對象轉(zhuǎn)為字符串的方法,需要的朋友可以參考下2014-08-08