Skip to content

Instantly share code, notes, and snippets.

@VertigoRay
Last active January 15, 2017 06:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VertigoRay/7b73da2cace3d49a2cf2 to your computer and use it in GitHub Desktop.
Save VertigoRay/7b73da2cace3d49a2cf2 to your computer and use it in GitHub Desktop.
The `$MyInvocation.ScriptLineNumber` variable is not the Current Line Number. It’s the Line number from where the function that you’re in was called. Actual line numbers can be caught for an error if you catch them. Used in this comment: http://goo.gl/7oeSEL
function a {
param(
[string]$UninstallString = 'thing'
)
$MyInvocation
Write-Host -Fore Cyan "$($here.File) $($MyInvocation.MyCommand):$($MyInvocation.ScriptLineNumber)"
b
try {
Throw('Thing!!!!')
} catch {
Write-Host -Fore Magenta ("{0} {1}:{2}: ErRaWr!! $_" -f @($here.File, $MyInvocation.MyCommand, $_.InvocationInfo.ScriptLineNumber))
}
}
function b {
$MyInvocation
Write-Host -Fore Cyan "$($here.File) $($MyInvocation.MyCommand):$($MyInvocation.ScriptLineNumber)"
}
# Buiding a $this style variable, but $this is an auto variable.
$here = @{
'File'='Test'
}
Write-Host -Fore Cyan "$($here.File) $($MyInvocation.MyCommand):$($MyInvocation.ScriptLineNumber)"
a
Write-Host -Fore Cyan "$($here.File) $($MyInvocation.MyCommand):$($MyInvocation.ScriptLineNumber)"
@VertigoRay
Copy link
Author

Output

Test CatchLineNumbers.ps1:1


MyCommand             : a
BoundParameters       : {}
UnboundArguments      : {}
ScriptLineNumber      : 23
OffsetInLine          : 1
HistoryId             : 137
ScriptName            : C:\Users\ras0196\test.ps1
Line                  : a

PositionMessage       : At C:\Users\ras0196\test.ps1:23 char:1
                        + a
                        + ~
PSScriptRoot          : C:\Users\ras0196
PSCommandPath         : C:\Users\ras0196\test.ps1
InvocationName        : a
PipelineLength        : 1
PipelinePosition      : 1
ExpectingInput        : False
CommandOrigin         : Internal
DisplayScriptPosition :

Test a:23
MyCommand             : b
BoundParameters       : {}
UnboundArguments      : {}
ScriptLineNumber      : 8
OffsetInLine          : 5
HistoryId             : 137
ScriptName            : C:\Users\ras0196\test.ps1
Line                  :     b

PositionMessage       : At C:\Users\ras0196\test.ps1:8 char:5
                        +     b
                        +     ~
PSScriptRoot          : C:\Users\ras0196
PSCommandPath         : C:\Users\ras0196\test.ps1
InvocationName        : b
PipelineLength        : 1
PipelinePosition      : 1
ExpectingInput        : False
CommandOrigin         : Internal
DisplayScriptPosition :

Test b:8
Test a:23
Test CatchLineNumbers.ps1:1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment