Reputation: 23503
I'm trying to get the line number of an error when running a PowerShell script. Here is what I'm using at the moment:
$e = $_.Exception
$line = $_.Exception.InvocationInfo.ScriptLineNumber
$msg = $e.Message
Write-Host -ForegroundColor Red "caught exception: $e at $line"
Sometimes this works and sometimes it doesn't. I'm wondering if I'm doing anything wrong, or what I can do to make this work more consistently.
Upvotes: 26
Views: 33608
Reputation: 204
here's another useful way to capture a detailed exception
try
{
throw "fdsfds"
}
catch
{
Write-Error ($_.Exception | Format-List -Force | Out-String) -ErrorAction Continue
Write-Error ($_.InvocationInfo | Format-List -Force | Out-String) -ErrorAction Continue
throw
}
Upvotes: 13
Reputation: 23503
I figured out what the issue was:
Instead of:
$e = $_.Exception
#this is wrong
$line = $_.Exception.InvocationInfo.ScriptLineNumber
$msg = $e.Message
Write-Host -ForegroundColor Red "caught exception: $e at $line"
$e = $_.Exception
$line = $_.InvocationInfo.ScriptLineNumber
$msg = $e.Message
Write-Host -ForegroundColor Red "caught exception: $e at $line"
Upvotes: 43