Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get powershell exception descriptions into a string?

I want to have access to the same message that Powershell prints when you send an error record to the output stream

Example:

This is the exception message At C:\Documents and Settings\BillBillington\Desktop\psTest\exThrower.ps1:1 char:6 + throw <<<< (New-Object ArgumentException("This is the exception")); + CategoryInfo : OperationStopped: (:) [], ArgumentException + FullyQualifiedErrorId : This is the exception

I when a get the last ErrorRecord by doing $Error[0] I can't seem to figure out how to get this information in a simple way

I found this 'Resolve-Error' function from the community extensions here which does roughly what I want but it prints a huge semi-formatted list of stuff I don't need that I have to then strip

Is there way of accessing the message that Powershell uses or failing that a simpler way of getting hash of the values I care about so I can put them into a string in a format of my choosing?

like image 869
Willbill Avatar asked Aug 04 '10 10:08

Willbill


People also ask

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 you write error messages in PowerShell?

To write a non-terminating error, enter an error message string, an ErrorRecord object, or an Exception object. Use the other parameters of Write-Error to populate the error record. Non-terminating errors write an error to the error stream, but they do not stop command processing.

How do I get the PowerShell error log?

In order to log or report an error, you first need to capture the error. This is called error handling. The most common way to handle a PowerShell error is using the try/catch blocks. The catch block is only invoked when the error is a Terminating Error.


1 Answers

If you want a bit shorter message (more user friendly sometimes?) than @tomasr suggests this will do:

$error[0].ToString() + $error[0].InvocationInfo.PositionMessage

You will get something like:

Cannot find path 'C:\TEMP\_100804_135716\missing' because it does not exist.
At C:\TEMP\_100804_135716\test.ps1:5 char:15
+   Get-ChildItem <<<<  missing

This technical info will be excluded:

+ CategoryInfo          : ObjectNotFound: (C:\TEMP\_100804_135716\missing:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
like image 105
Roman Kuzmin Avatar answered Oct 06 '22 19:10

Roman Kuzmin