DirectoryEntry 和域控制器

DirectoryEntry and Domain Controller

我们在 Powershell 中有一个脚本,我们可以在其中操纵 Active Directory。我现在用 C# 编写了它。我的同事说他们必须在 PS 中指定域控制器,否则可能会发生您使用 DC A 读取并在 DC B 上写入的情况,这可能会导致问题。

如果我使用 DirectorySearcher 查找条目并对其进行操作,我真的必须指定域控制器吗?或者根据定义,同一域控制器是否是用于查找对象 (DirectorySearcher) 并保存它 (CommitChanges) 的用户?

我不这么认为,因为我只能在搜索部分(DirectorySearcher 的 DirectoryEntry 对象)指定它,而不是在它写回 AD 时(CommitChanges)。所以我假设同一个 DC 用于写入和用于读取的一样。

下面是一个示例,我在其中搜索特定条目并更改 属性。

string filter = "(proxyaddresses=SMTP:johndoe@abc.com)";
string searchOU = "ou=Users,dc=abc,dc=com";

DirectoryEntry entry = new DirectoryEntry("LDAP://" + searchOU);
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = filter;
SearchResult result = search.FindOne();
search.Dispose();
entry.Close();

DirectoryEntry toContact = result.GetDirectoryEntry();    
toContact.Properties["showInAddressBook"].Value = addressbook; 
toContact.CommitChanges();
toContect.Close();

我可以推荐使用 System.DirectoryServices.AccountManagement 命名空间中可用的对象吗?它是 .NET 的最新补充,可以更优雅地处理 AD 工作。它最近让我免去了很多心痛,而旧的 DirectorySearcher 做事的方式在一定程度上是造成这种心痛的原因。让框架承受压力!网络上有很多非常有用的文章,例如 here.

作为如何使用 PrincipalContext 搜索活动目录的示例,试试这个:

var adContext = new PrincipalContext(ContextType.Domain);
var queryTemplateUser = new UserPrincipal(adContext);
queryTemplateUser.SamAccountName = "HenryCrunn";
var ldapSearcher = new PrincipalSearcher(queryTemplateUser);
var searchResults = ldapSearcher.FindAll();