将ExtendedTypeSystemException转换为字符串

我正在尝试将异常消息转换为字符串,我可以throw也可以写到事件管理器,但是有严重的问题。

尝试了How can I get powershell exception descriptions into a string?,但是这里没有任何作用。

这就是我用来验证网络上凭据的方法:

$user = 'user'
$pass = 'pass'
$domain = "ldap://" + ( [ADSI]"" ).DistinguishedName

$creds = New-Object System.Management.Automation.PSCredential("$($env:USERDOMAIN)\$user",$(ConvertTo-SecureString $pass -AsPlainText -Force))

New-Object System.DirectoryServices.DirectoryEntry ($domain,$user,$creds.GetNetworkCredential().Password)

如果凭据有效,您将得到类似的回信:

distinguishedName : {DC=COMP}
Path              : LDAP://COMP

如果有错误,它将类似于:

format-default : The following exception occurred while retrieving member
"distinguishedName": "Unknown error (0x80005000)"
     + CategoryInfo          : NotSpecified: (:) [format-default],ExtendedTypeSystemException
     + FullyQualifiedErrorId : CatchFromBaseGetMember,microsoft.PowerShell.Commands.FormatDefaultCommand

关于我只能用该输出执行的唯一操作是放下format-default

关于如何获得最高收入的任何建议?

到目前为止,我已经尝试过单独或组合使用$PSItem$_.Exceptionmessage.ToString()| Out-String[string]

lcz197474 回答:将ExtendedTypeSystemException转换为字符串

该错误有些棘手,因为New-Object不会抛出该错误,实际上,该对象的创建就很好。该错误实际上发生在PowerShell试图在控制台上显示该对象并且找不到该对象的默认显示格式所需的属性(在这种情况下为DistinguishedName)时。因此,不能通过将New-Object放在try..catch语句中来捕获它。

该错误在发生后确实会出现在自动变量$error中,因此您可以检查$error[0]以获得更多信息(例如,使用$error[0].Message仅获取错误消息),但是您无法阻止错误消息而不首先避免发生错误(因为它仅在尝试显示对象时发生)。

更好的方法可能是在变量中捕获创建的对象,然后检查属性DistinguishedName的存在。

$o = New-Object DirectoryServices.DirectoryEntry ($domain,$user,$pass)
if ($o.DistinguishedName) {
    'Invalid credentials'
}

顺便说一句,从纯文本密码创建一个安全的字符串,然后再次解密,因为您需要纯文本密码是没有意义的。


编辑:

我进一步研究了此问题,如果由于某种原因必须从PowerShell的默认输出格式中获取实际的错误消息,则可以这样进行:

$o = New-Object DirectoryServices.DirectoryEntry ($domain,$pass)

try {
    $o | Out-Default
} catch {
    $_.Exception.InnerException.Message
}
本文链接:https://www.f2er.com/3117030.html

大家都在问