How to get the line number of error in PowerShell
here's another useful way to capture a detailed exception
try
{
throw "fdsfds"
}
catch
{
Write-Error ($_.Exception | Format-List -Force | Out-String) -ErrorAction Continue
Write-Error ($_.InvocationInfo | Format-List -Force | Out-String) -ErrorAction Continue
throw
}
I figured out what the issue was:
Instead of:
$e = $_.Exception
#this is wrong
$line = $_.Exception.InvocationInfo.ScriptLineNumber
$msg = $e.Message
Write-Host -ForegroundColor Red "caught exception: $e at $line"
It should be
$e = $_.Exception
$line = $_.InvocationInfo.ScriptLineNumber
$msg = $e.Message
Write-Host -ForegroundColor Red "caught exception: $e at $line"