Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the line number of error in PowerShell

Tags:

I'm trying to get the line number of an error when running a PowerShell script. Here is what I'm using at the moment:

$e = $_.Exception
$line = $_.Exception.InvocationInfo.ScriptLineNumber
$msg = $e.Message 

Write-Host -ForegroundColor Red "caught exception: $e at $line"

Sometimes this works and sometimes it doesn't. I'm wondering if I'm doing anything wrong, or what I can do to make this work more consistently.

like image 424
BlackHatSamurai Avatar asked Jun 21 '13 02:06

BlackHatSamurai


People also ask

How do I get line numbers in PowerShell?

To count the total number of lines in the file in PowerShell, you first need to retrieve the content of the item using Get-Content cmdlet and need to use method Length() to retrieve the total number of lines.

How do I get error details in PowerShell?

You can use Get-Error to display a specified number of errors that have occurred in the current session using the Newest parameter. The Get-Error cmdlet also receives error objects from a collection, such as $Error , to display multiple errors from the current session.

How do I get the PowerShell error log?

You can use the Get-EventLog parameters and property values to search for events. The cmdlet gets events that match the specified property values. PowerShell cmdlets that contain the EventLog noun work only on Windows classic event logs such as Application, System, or Security.

How do I get an exception message in PowerShell?

GetType(). FullName to view the exception message for the last error that occurred. Going back to the PowerShell console, rerun the New-Item command with a non-existent path, then run the $Error command to find the exception message.


1 Answers

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"
like image 119
BlackHatSamurai Avatar answered Sep 29 '22 14:09

BlackHatSamurai