2012-03-09 270 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