捕获PowerShell脚本内部的异常


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

本文链接: https://www.pstips.net/catch-exception-from-internal-script.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注