PowerShell腳本trap語句捕獲異常寫法實例
更新時間:2014年07月02日 09:12:16 投稿:junjie
這篇文章主要介紹了PowerShell腳本trap語句捕獲異常寫法實例,包含幾個代碼實例,需要的朋友可以參考下
先看一個腳本文件: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
The term 'Get-FanBingbing' is not recognized as the name of a cmdlet
接下來我把3.three.test.ps1腳本文件的內(nèi)容改成:
復(fù)制代碼 代碼如下:
dir D:\ShenMaDoushiFuYun #目錄不存在
再運行,這時沒有捕獲到異常,錯誤為:dir : Cannot find path ‘D:\ShenMaDoushiFuYun' because it does not exist.
于是我想是不是因為終止錯誤與非終止錯誤的區(qū)別:所以還寫了try catch捕獲語句,雙管齊下:
復(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.
看來問題不在這里。事實上是ErrorActionReference的問題,這樣改就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.
簡單分析:
像Get-FanBingbing這樣的異常,是因為命令不存在,確切來講屬于語法錯誤,級別比較高被trap到了。但是像目錄找不到這樣的異常,相對而言級別比較低,默認不能捕獲到,除非顯示指定ErrorAction為stop。
相關(guān)文章
PowerShell創(chuàng)建Byte數(shù)組例子
這篇文章主要介紹了PowerShell創(chuàng)建Byte數(shù)組例子,Byte數(shù)組即字節(jié)數(shù)組,它是一種強類型的數(shù)組,需要的朋友可以參考下2014-08-08PowerShell實現(xiàn)統(tǒng)計函數(shù)嵌套深度
這篇文章主要介紹了PowerShell實現(xiàn)統(tǒng)計函數(shù)嵌套深度,本文分享一個函數(shù),可以實現(xiàn)統(tǒng)計腳本執(zhí)行的嵌套層次,需要的朋友可以參考下2015-06-06Powershell獲取系統(tǒng)中所有可停止的服務(wù)
這篇文章主要介紹了Powershell獲取系統(tǒng)中所有可停止的服務(wù),本文直接給出實現(xiàn)代碼,需要的朋友可以參考下2015-03-03PowerShell中字符串使用單引號和雙引號的區(qū)別
這篇文章主要介紹了PowerShell中字符串使用單引號和雙引號的區(qū)別,大家可能會經(jīng)常遇到這個問題,需要的朋友可以參考下2014-08-08PowerShell中的特殊變量$null介紹和創(chuàng)建多行注釋小技巧
這篇文章主要介紹了PowerShell中的特殊變量$null介紹和創(chuàng)建多行注釋小技巧,需要的朋友可以參考下2014-08-08