您的位置:首页 > 运维架构 > Shell

PowerShell脚本trap语句捕获异常写法实例

2014-07-02 09:12 561 查看

先看一个脚本文件: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脚本文件的内容改成:
复制代码 代码如下: dir D:\ShenMaDoushiFuYun #目录不存在
再运行,这时没有捕获到异常,错误为:dir : Cannot find path ‘D:\ShenMaDoushiFuYun' because it does not exist.

于是我想是不是因为终止错误与非终止错误的区别:所以还写了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到了。但是像目录找不到这样的异常,相对而言级别比较低,默认不能捕获到,除非显示指定ErrorAction为stop。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息