欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PowerShell腳本trap語句捕獲異常寫法實(shí)例

 更新時(shí)間:2014年07月02日 09:12:16   投稿:junjie  
這篇文章主要介紹了PowerShell腳本trap語句捕獲異常寫法實(shí)例,包含幾個(gè)代碼實(shí)例,需要的朋友可以參考下

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

簡(jiǎn)單分析:
像Get-FanBingbing這樣的異常,是因?yàn)槊畈淮嬖?,確切來講屬于語法錯(cuò)誤,級(jí)別比較高被trap到了。但是像目錄找不到這樣的異常,相對(duì)而言級(jí)別比較低,默認(rèn)不能捕獲到,除非顯示指定ErrorAction為stop。

相關(guān)文章

最新評(píng)論