Powershell - Retrieve inner exception to output (socketException)

时光总嘲笑我的痴心妄想 提交于 2020-03-02 19:31:11

问题


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?


回答1:


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.




回答2:


this?

"$($Error[0].Exception.InnerException.message): $computername"

The behaviour you have IMHO is due to the custom formatting file



来源:https://stackoverflow.com/questions/24651213/powershell-retrieve-inner-exception-to-output-socketexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!