BlackHatSamurai
BlackHatSamurai

Reputation: 23503

How to get the line number of error in PowerShell

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

Answers (2)

Abu Belal
Abu Belal

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

BlackHatSamurai
BlackHatSamurai

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"

It should be

$e = $_.Exception
$line = $_.InvocationInfo.ScriptLineNumber
$msg = $e.Message 

Write-Host -ForegroundColor Red "caught exception: $e at $line"

Upvotes: 43

Related Questions