gpt4 book ai didi

powershell - 如何在 PowerShell 中通过 FullyQualifiedErrorId 进行捕获?

转载 作者:行者123 更新时间:2023-12-02 17:43:02 27 4
gpt4 key购买 nike

我有一个脚本可以创建新的 AD 对象(碰巧是通过 New-ADObject)。如果该对象已经存在,我需要捕获并处理它。但是,异常类型并不像 FullyQualifiedErrorId 那样明确。请注意以下事项:

> $Error[-1] | Format-List -Property * -Force

writeErrorStream : True
PSMessageDetails :
Exception : Microsoft.ActiveDirectory.Management.ADException: An attempt was made to add an object to the directory with
a name that is already in use ---> System.ServiceModel.FaultException: The supplied entry already exists.
--- End of inner exception stack trace ---
at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowExceptionForExtendedError(String
extendedErrorMessage, Exception innerException)
at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowExceptionForFaultDetail(FaultDetail
faultDetail, FaultException faultException)
at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowException(AdwsFault adwsFault, FaultException
faultException)
at Microsoft.ActiveDirectory.Management.AdwsConnection.Create(ADAddRequest request)
at Microsoft.ActiveDirectory.Management.ADWebServiceStoreAccess.Microsoft.ActiveDirectory.Management.IADSy
ncOperations.Add(ADSessionHandle handle, ADAddRequest request)
at Microsoft.ActiveDirectory.Management.ADActiveObject.Create()
at Microsoft.ActiveDirectory.Management.Commands.ADNewCmdletBase`3.ProcessRecordOverride()
at Microsoft.ActiveDirectory.Management.Commands.ADCmdletBase.ProcessRecord()
TargetObject : ou=Domain Controllers,DC=cryotest,DC=testdom
CategoryInfo : NotSpecified: (ou=Domain Contr...test,DC=afcdom1:String) [New-ADObject], ADException
FullyQualifiedErrorId : An attempt was made to add an object to the directory with a name that is already in
use,Microsoft.ActiveDirectory.Management.Commands.NewADObject
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at Import-ADObjectOfClass, C:\Users\administrator\Desktop\Import-ADObjects.ps1: line 103
at <ScriptBlock>, C:\Users\administrator\Desktop\Import-ADObjects.ps1: line 137
at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {1, 1}

如何在我的 Catch block 中使用这里更详细的信息?

最佳答案

FullyQualifiedErrorId 只是异常对象的 .Message 属性以及引发异常的类的完全限定名称。

你不能通过 FullyQualifiedErrorId 来捕获,但是你可以通过异常类型来捕获:

try {
# Do something that causes the 'name already in use' exception you're getting.
} catch [System.ActiveDirectory.Management.ADException] {
if ($_.Exception.Message -ilike "*already in use") {
# Do something to handle the error condition.
}
}

请注意,这不是跨不同语言的可移植解决方案,因为异常消息可能会在非英语版本的 Windows 上进行本地化。

此外,您可能必须修改 try block 以包含 -ErrorAction Stop 以确保捕获到错误。

关于powershell - 如何在 PowerShell 中通过 FullyQualifiedErrorId 进行捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18136962/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com