我希望在使用 .NET (C#) 使用普通
DirectoryEntry
. 更新 Active Directory 自定义属性方面取得突破
我有一个古老的 AD 集成,可以毫无问题地定期更新大量开箱即用的属性。最近,AD 团队向需要使用适当值更新的 AD 用户记录添加了两个新的自定义属性(可为空的布尔类型和日期时间类型)。这些属性没有初始值,并且在使用 MS AD 管理中心查看它们时“未设置”。我可以使用该工具手动修改新属性而不会出现问题。
在解决方案中,我们进行
DirectorySearcher
调用以获取所需的SearchResult
,加载所需的属性。一切都在那里,包括自定义属性及其当前值。
接下来,我们用
DirectoryEntry
抓住SearchResult.GetDirectoryEntry()
。从这里,我可以更新所有普通属性,但是虽然我可以 see DirectoryEntry.Properties.PropertyNames
集合中的新自定义属性,但我无法以任何方式访问它们以读取它们的值或执行所需的更新。
如果我将手表添加到
DirectoryEntry.Properties.Values
集合中,它会出错:
未知错误(0x8000500c)
就像他们不存在一样。
当我尝试获取值时,出现错误:
'entryToChange.Properties["TheCustomAttributeName"]' 抛出类型为'System.Runtime.InteropServices.COMException'的异常
但是,正如我提到的,如果我访问类似的内容
entryToChange.Properties["SamAccountName"][0]
我看到了预期的值并且可以毫无问题地更新它。
接下来,我进入 Powershell, 能够使用
set-AdUser
毫无问题地更新其中一个新的自定义属性。我的大脑爆炸了......眼睛向后翻......等等
关于使用 .NET 和典型的
DirectoryEntry
类更新 AD 中的新自定义属性,我缺少什么?提前感谢您的任何见解。
这是代码的简化片段:
using (DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry, adQueryFilter, adAttributesToLoad)))
{
SearchResult searchResult = directorySearcher.FindOne();
if (searchResult != null)
{
using (DirectoryEntry entryToChange = searchResult.GetDirectoryEntry())
{
// BOOM! The error throws right here, when I try to look at the custom attribute
if (entryToChange.Properties["TheCustomAttribute"] != null &&
entryToChange.Properties["TheCustomAttribute"].Any())
{
// We never get down here to do the update...
entryToChange.Properties["TheCustomAttribute"][0] = "The new value";
}
}
}
}
我的猜测是它不喜欢使用
.Any()
。我什至无法用.Any()
编译它(即使我有using System.Linq
)。
您可以使用
.Contains()
来检查属性是否有值。如果它没有值,那么它将返回false
.
如果是单值属性,也可以使用
.Value
来设置值
if (entryToChange.Properties.Contains("TheCustomAttribute"))
{
entryToChange.Properties["TheCustomAttribute"].Value = "The new value";
}
如果还是有异常,查看
COMException
的属性看有没有错误码