我想检查一个用户是否在特定的父OU中.
我怎样才能做到这一点?
using System.DirectoryServices.AccountManagement; public bool IsUserInOU(string samAccountName,string OUName){ using (var context = new PrincipalContext(ContextType.Domain)) { using (var user = UserPrincipal.FindByIdentity(context,IdentityType.SamAccountName,samAccountName)) { //Check if the user is in the OU specified in OUName //Something like: //return user.IsInOU(OUName); } } } public void TestIt_1(){ //The parent OU of this user is "AwesomeOU" string samAccountName = "Joe"; string OUName = "AwesomeOU"; bool expected = true; bool actual = IsUserInOU(samAccountName,OUName); Assert.AreEqual(expected,actual); } public void TestIt_2(){ //The parent OU of this user is "WhateverOU" string samAccountName = "Mike"; string OUName = "AwesomeOU"; bool expected = false; bool actual = IsUserInOU(samAccountName,actual); }
域名:
>国家OU
>真棒OU
乔
>无论OU
>迈克
empi答案后的解决方案1
使用empi给出的信息,我写了以下方法来提取DistinguishedName中的第一个OU.做到这一点,其余的是轻而易举.
public static string GetOUForUser(string samAccountName) { using (var context = new PrincipalContext(ContextType.Domain)) { using (var user = UserPrincipal.FindByIdentity(context,samAccountName)) { //System.Console.WriteLine(user.DistinguishedName); int startIndex = user.DistinguishedName.IndexOf("OU=",1) + 3; //+3 for length of "OU=" int endIndex = user.DistinguishedName.IndexOf(",",startIndex); var group = user.DistinguishedName.Substring((startIndex),(endIndex - startIndex)); return group; } } }
JPBlanc答复后的解决方案2
public static string GetOUForUser(string samAccountName) { using (var context = new PrincipalContext(ContextType.Domain)) { using (var user = UserPrincipal.FindByIdentity(context,samAccountName)) { using (DirectoryEntry deUser = user.GetUnderlyingObject() as DirectoryEntry) { using (DirectoryEntry deUserContainer = deUser.Parent) { return deUserContainer.Properties["Name"].Value.ToString(); } } } } }
解决方法
Ok @Empi解决方案正在运行,但是UserPrincipal构建在DirectoryEntry对象上,该对象提供了一个父或容器属性,只需要给出您要查找的对象,而不使用字符串方式.
/* Retreiving a principal context */ PrincipalContext domainContext = new PrincipalContext(ContextType.Domain,"WM2008R2ENT:389","dc=dom,dc=fr","dom\\jpb","MyPwd"); /* Retreive a user */ UserPrincipal user = UserPrincipal.FindByIdentity(domainContext,"user1"); /* Retreive the container */ DirectoryEntry deUser = user.GetUnderlyingObject() as DirectoryEntry; DirectoryEntry deUserContainer = deUser.Parent; Console.WriteLine (deUserContainer.Properties["distinguishedName"].Value);