How to display line numbers where Powershell exceptions are raised

Viewed 416

My Powershell script is throwing an exception, but not giving me the line number where the exception is thrown:

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

I would think the best practice here is to refactor the script to use try/catch blocks to narrow down exactly where the Set-Content exception is being thrown - but in this case, due to the size/scope of the script, I am trying to avoid that option.

Instead, I'm hoping for a bit of a top-down solution - for instance, being able to call the script with added verbosity, in such a way that Powershell prints the line numbers in the stack traces (pretty sure Python does this by default).

Does Powershell 3.0 natively support this?

EDIT: The accepted answer to this question involves the try/catch approach, which I have mentioned is not my preferred approach. Again, is there some way to get PowerShell to report line numbers when exceptions are raised without mandatory try/catches? Would I have to wrap the entire script in a generic try/catch? Would I have to invoke the script with some --verbose flag? Does Powershell 3.0 support anything like that?

1 Answers

Set-PsDebug is going to print every command one the console, while a script is running.

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
Related