pizi
pizi

Reputation: 113

How to get line number with error inside trap in powershell?

I use trap to write errors to file, and want write line number where error ocured.

$_.Exception.StackTrace is not answer.

Where I can get line number of error? Maybe some predefined variable?

Upvotes: 11

Views: 13056

Answers (3)

Rustam
Rustam

Reputation: 468

If you just want to find an error line after the script has been executed, you can view $Error array. $Error[0] corresponds to the last error.

More details here.

Upvotes: -1

Roman Kuzmin
Roman Kuzmin

Reputation: 42063

You should use $_.InvocationInfo properties, for example: ScriptName, ScriptLineNumber, OffsetInLine, Line.

For example to format position info in Visual Studio style:

trap {
    Write-Host "$($_.InvocationInfo.ScriptName)($($_.InvocationInfo.ScriptLineNumber)): $($_.InvocationInfo.Line)"
}

It will write something like:

C:\TEMP\test2.ps1(8): Get-Item missing

Also, you can just use $_.InvocationInfo.PositionMessage, see this post: How can I get powershell exception descriptions into a string?

Upvotes: 8

kbrimington
kbrimington

Reputation: 25692

You can retrieve the line number from the InvocationInfo object on $_. For example, the script...

"Hello, World!"

function foo() {
  trap [Exception] {
    $_.InvocationInfo.ScriptLineNumber
    $_.InvocationInfo.OffsetInLine
    continue;
  }

  [reflection.assembly]::loadfrom("C:\")
}

foo

... generates the output:

Hello, World!
10
34

Upvotes: 14

Related Questions