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?
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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With