当前位置: 移动技术网 > IT编程>脚本编程>Shell > PowerShell脚本trap语句捕获异常写法实例

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

先看一个脚本文件: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。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网