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。
相关文章
探索PowerShell (四) PowerShell的对象、格式与参数
本节将要给大家介绍一下PowerShell下的对象,基本格式以及参数。依然属于PowerShell的基础2012-12-12
PowerShell和FFmpeg查找Windows中所有损坏音频文件
这篇文章主要为大家介绍了Windows中查找出所有损坏的音频文件,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-10-10


最新评论