2012-03-09 268 views
7

SAM帳戶我有這樣的代碼:搜索用通配符

public static DataTable ExecutesAMAccountNameQuery(string sAMAccountName) 
     { 
      string filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" + sAMAccountName + "))"; 
      return ExecuteADQuery("GC:", filter); 
     } 

它僅與用戶全名,我不知道語法,使其與通配符在SQL工作,就像一個喜歡的藝術品?

感謝

回答

22

如果您使用.NET 3.5或更高版本,可以使用PrincipalSearcher和「查詢通過例如」主要做你的搜索:

// create your domain context 
PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 

// define a "query-by-example" principal - here, we search for a UserPrincipal 
UserPrincipal qbeUser = new UserPrincipal(ctx); 
qbeUser.SamAccountName = "Esteban*"; 

// create your principal searcher passing in the QBE principal  
PrincipalSearcher srch = new PrincipalSearcher(qbeUser); 

// find all matches 
foreach(var found in srch.FindAll()) 
{ 
    // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....   
} 

如果你的避風港已經 - 絕對閱讀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的「查詢範例」。

+0

我只維護一些現有的代碼,所以我不想用你發給我的代碼弄亂很多,但是這個我想我可以把*放在開始和結束,它也應該工作。 – 2012-03-09 13:55:42

+0

是這樣的:sAMAccountName = *「+ sAMAccountName +」*) – 2012-03-09 13:56:25

+0

@EstebanV .: [根據此](http://technet.microsoft.com/en-us/library/ee198823.aspx)它似乎應該工作,是的。 – 2012-03-09 13:57:28