我有一个脚本可以创建新的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块中使用更详细的信息?
答案 0 :(得分:4)
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块以包含-ErrorAction Stop
以确保捕获错误。
答案 1 :(得分:1)
如果New-ADObject
引发的错误不是使用catch的终止错误将无济于事。您可以做的一件事是使用ErrorAction参数使错误成为终止错误:
try{
New-ADObject ... -ErrorAction Stop
}
catch{
... handle the error ....
}
答案 2 :(得分:0)
我不知道您是否可以通过FullyQualifiedErrorId
捕获异常,但是我找到了这种方法来获取它,并且对我有用:
$InerrMessage= $_.FullyQualifiedErrorId