Powershell - Retrieve inner exception to output (socketException)
.net, error-handling, exception, powershell
Solution
I believe the difference is which method Powershell is calling to get the output from the object in different circumstances.
When you just output it to the pipeline by using
$error[0].exception.innerexception
it's calling the `.GetBaseException()` method, which just outputs the Message property.
When you cast it as [string] to use with Write-Host, it's calling the `.tostring()` method, which is outputting all of the error information.
Problem
I have recently started digging into error handling in Powershell and I noticed something that I do not really understand (I cannot tell where this behaviour is coming from). I have a simple function, which checks for domain name using `[System.Net.DNS]::GetHostByName()` If this variable gets passed a non-existing host, it throws a nasty error `Exception calling "GetHostByName" with "1" argument(s): "No such host is known"` I then want to catch the error and do some cosmetics around it `$Error[0].Exception.InnerException` gives a really nice output: `No such host is known` and nothing else - which I like, and I want it to be the message appearing instead of error. When I place the above in the catch clause, everything works fine. But how surprised I was when I saw that putting semicolons, or using `Write-host` or in any way converting that to 'string' value, messes up the innerException. Try it for yourself: - cause a SocketException using the 'wrong' name - See what `$Error[0].Exception.InnerException` throws - See what `"$($Error[0].Exception.InnerException)"` throws The first command gives the `No such host is known` while the second command gives the complete error. Please explain me why is this happening? Finally, I would want the error message to popup: `No such host is known: $computername`. Is there 'easy' way to do this rather than doing bloody regular expressions?