【发布时间】:2019-06-14 21:43:56
【问题描述】:
我的 Powershell 脚本抛出异常,但没有给出抛出异常的行号:
The process cannot access the file 'C:/path/to/foo.txt' because it is being used by another process.
+ CategoryInfo : NotSpecified: (:) [Set-Content], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.SetContentCommand
+ PSComputerName : localhost
我认为这里的最佳做法是重构脚本以使用 try/catch 块来缩小引发 Set-Content 异常的确切位置 - 但在这种情况下,由于脚本的大小/范围,我试图避免这种选择。
相反,我希望有一个自上而下的解决方案——例如,能够以增加冗长的方式调用脚本,以便 Powershell 打印堆栈跟踪中的行号(非常确定 Python默认情况下会这样做)。
Powershell 3.0 本身是否支持此功能?
编辑:接受的答案 to this question 涉及 try/catch 方法,我已经提到这不是我的首选方法。同样,是否有某种方法可以让 PowerShell 在没有强制尝试/捕获的情况下引发异常时报告行号?我是否必须将整个脚本包装在通用的 try/catch 中?我是否必须使用一些 --verbose 标志调用脚本? Powershell 3.0 是否支持类似的东西?
【问题讨论】:
-
能否添加导致错误的脚本?
-
应该有
At D:\PShell\SO\56588150.ps1:21 char:1行(或类似行)。您可以查看$Error[0].ScriptStackTrace的属性。 -
或者,
$Error[0].InvocationInfo.ScriptLineNumber -
@Moerwald 这不是那个问题的重复 - 接受的答案涉及 try/catch 块方法(
$_.Exception在 catch 块的上下文中被调用)。