我之前发过一个问题,可能是我没有描述清楚我的问题,所以我重写了我的问题,希望大家能够理解。
在我的 Windows 服务器中,大约有 1500 个用户,Active Directory 中的用户信息不正确,需要更新。邮箱字段要更新,比如当前邮箱是tom.chan@email.com
,我想改成“用户名”+email.com
例如:
tom.chan@email.com
==> user1@email.com
;
amy.yuen@email.com
==> user2@email.com
;
jacky.hung@email.com
==> user3@email.com
谁能帮忙出出主意?提前谢谢你。
您可以使用 PrincipalSearcher
和“query-by-example”主体进行搜索:
// 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它很好地展示了如何充分利用 System.DirectoryServices.AccountManagement
中的新功能。或者查看 MSDN documentation on the System.DirectoryServices.AccountManagement命名空间。
当然,根据您的需要,您可能希望在您创建的“按示例查询”用户主体上指定其他属性:
DisplayName
(通常:名字 + 空格 + 姓氏)
SAM 帐户名
- 您的 Windows/AD 帐户名
User Principal Name
- 您的“username@yourcompany.com”样式名称
您可以在 UserPrincipal
上指定任何属性,并将它们用作您的 PrincipalSearcher
的“按示例查询”。