如何显示引发 Powershell 异常的行号

How to display line numbers where Powershell exceptions are raised

我的 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 异常的确切位置 - 但在这种情况下,由于 size/scope 的脚本,我试图避免该选项。

相反,我希望有一些自上而下的解决方案——例如,能够以更详细的方式调用脚本,这样 Powershell 就可以在堆栈跟踪中打印行号(漂亮当然 Python 默认会这样做)。

Powershell 3.0 本身支持吗?

编辑:接受的答案to this question 涉及try/catch 方法,我已经提到这不是我的首选方法。同样,是否有某种方法可以让 PowerShell 在没有强制性 try/catches 的情况下引发异常时报告行号?我是否必须将整个脚本包装在一个通用的 try/catch 中?我是否必须使用一些 --verbose 标志来调用脚本? Powershell 3.0 是否支持类似的东西?

Set-PsDebug 将在控制台打印每个命令,而脚本是 运行。

Set-PSDebug -Trace 2; foreach ($i in 1..3) {$i}
DEBUG:    1+ Set-PsDebug -Trace 2; foreach ($i in 1..3) {$i}
DEBUG:    1+ Set-PsDebug -Trace 2; foreach ($i in 1..3) {$i}
1
DEBUG:    1+ Set-PsDebug -Trace 2; foreach ($i in 1..3) {$i}
2
DEBUG:    1+ Set-PsDebug -Trace 2; foreach ($i in 1..3) {$i}
3