您可以使用 aPrincipalSearcher
和“按示例查询”主体进行搜索:
// create your domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// define a "query-by-example" principal - here, we search for a UserPrincipal
// with last name (Surname) that starts with "A"
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.Surname = "A*";
// create your principal searcher passing in the QBE principal
using (PrincipalSearcher srch = new PrincipalSearcher(qbeUser))
{
// find all matches
foreach(var found in srch.FindAll())
{
// now here you need to do the update - I'm not sure exactly *WHICH*
// attribute you mean by "username" - just debug into this code and see
// for yourself which AD attribute you want to use
UserPrincipal foundUser = found as UserPrincipal;
if(foundUser != null)
{
string newEmail = foundUser.SamAccountName + "@email.com";
foundUser.EmailAddress = newEmail;
foundUser.Save();
}
}
}
}
使用这种方法,您可以遍历您的用户并更新它们 - 再次:我不完全确定我理解您想要用作新电子邮件地址的内容.....所以也许您需要调整它以适应您的需求。
另外:我建议不要一次对您的整个用户群执行此操作!以组的形式运行它,例如按 OU,或按姓氏的首字母或其他方式 - 不要一次对所有 1500 个用户进行大规模更新 - 将其分解为可管理的部分。
如果您还没有 - 一定要阅读 MSDN 文章Managing Directory Security Principals in the .NET Framework 3.5,它很好地展示了如何充分利用 .NET Framework 中的新功能System.DirectoryServices.AccountManagement
。或查看System.DirectoryServices.AccountManagement命名空间上的 MSDN 文档。
当然,根据您的需要,您可能希望在您创建的“示例查询”用户主体上指定其他属性:
DisplayName
(通常:名字 + 空格 + 姓氏)
SAM Account Name
- 您的 Windows/AD 帐户名称
User Principal Name
- 您的“username@yourcompany.com”样式名称
您可以在 上指定任何属性UserPrincipal
并将其用作PrincipalSearcher
.