tags:

views:

43

answers:

2

I use trap to write erors 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?

+2  A: 

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
kbrimington
+2  A: 

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: http://stackoverflow.com/questions/3404642/how-can-i-get-powershell-exception-descriptions-into-a-string

Roman Kuzmin