Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 933
pizi Avatar asked Aug 11 '10 11:08

pizi


2 Answers

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
like image 191
kbrimington Avatar answered Oct 08 '22 10:10

kbrimington


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?

like image 27
Roman Kuzmin Avatar answered Oct 08 '22 11:10

Roman Kuzmin