亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Powershell小技巧之捕獲腳本內(nèi)部的異常

 更新時(shí)間:2014年10月12日 13:46:49   投稿:hebedich  
這篇文章主要介紹了使用Powershell捕獲腳本內(nèi)部的異常的小技巧,需要的朋友可以參考下

先看一個(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

接下來我把3.three.test.ps1腳本文件的內(nèi)容改成:

復(fù)制代碼 代碼如下:

dir D:\ShenMaDoushiFuYun #目錄不存在

再運(yùn)行,這時(shí)沒有捕獲到異常,錯(cuò)誤為:dir : Cannot find path ‘D:\ShenMaDoushiFuYun' because it does not exist.

于是我想是不是因?yàn)榻K止錯(cuò)誤與非終止錯(cuò)誤的區(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.

看來問題不在這里。事實(shí)上是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這樣的異常,是因?yàn)槊畈淮嬖?,確切來講屬于語法錯(cuò)誤,級別比較高被trap到了。但是像目錄找不到這樣的異常,相對而言級別比較低,默認(rèn)不能捕獲到,除非顯示指定ErrorAction為stop。

相關(guān)文章

最新評論