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.
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.
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.
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.
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.
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"
$e = $_.Exception
$line = $_.InvocationInfo.ScriptLineNumber
$msg = $e.Message
Write-Host -ForegroundColor Red "caught exception: $e at $line"
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