25

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.

Robert Dyjas
  • 4,979
  • 3
  • 19
  • 34
BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
  • Are try catch statements not giving you the information you need? Is this in a catch? – Austin T French Jun 21 '13 at 02:39
  • No the try/catch only gives the error. It doesn't list the line number and stuff. – BlackHatSamurai Jun 21 '13 at 02:45
  • I guessed (Although no exceptions to catch now) that something like: catch {[Exception] $_.ScriptLineNumber } might do it... But I also just catch my errors and echo the exception and it generally gives me what I need. So I am glad you found it. – Austin T French Jun 21 '13 at 02:58
  • I was wrong, I am using a try/catch. This code is in the catch statement. – BlackHatSamurai Jun 21 '13 at 05:37
  • Possible duplicate of [Can I get detailed exception stacktrace in PowerShell?](https://stackoverflow.com/questions/795751/can-i-get-detailed-exception-stacktrace-in-powershell) – Michael Freidgeim Sep 06 '19 at 07:50

2 Answers2

40

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"
Liam
  • 27,717
  • 28
  • 128
  • 190
BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
12

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
}
sschoof
  • 1,531
  • 1
  • 17
  • 24
Abu Belal
  • 194
  • 2
  • 8