2013-02-15 78 views
2

我之前發佈過一個問題,但可能是我沒有清楚地描述我的問題,因此我重新編寫了我的問題,希望大家可以理解它。更新AD中的用戶信息

在我的Windows服務器中,大約有1500個用戶,Active Directory中的用戶信息不正確,需要更新。電子郵件字段應該更新,例如,當前的電子郵件是[email protected],我想將其更改爲"user name" + email.com

例如:

  1. [email protected] ==>[email protected];
  2. [email protected] ==>[email protected];
  3. [email protected] ==>[email protected]

可能有人能幫助提供意見?先謝謝你。

回答

1

您可以使用PrincipalSearcher和「查詢通過例如」主要做你的搜索:

// 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 Account Name - 你的Windows/AD帳戶名
  • User Principal Name - 你的 「[email protected]」 樣式名

可以SPE將UserPrincipal上的任何屬性都作爲屬性,並將它們用作您的PrincipalSearcher的「查詢範例」。