使用C#在Active Directory中获取用户的父OU OU#
问题描述:
我想检查用户是否在特定的父OU中。使用C#在Active Directory中获取用户的父OU 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, OUName);
Assert.AreEqual(expected, actual);
}
域:
- 国家OU
- 真棒OU
- 乔
- 无论OU
- 迈克·
- 真棒OU
EMPI的回答
与EMPI给出的信息后,解决方案1,我写了下面的方法提取的distinguishedName来第一个OU。完成之后,剩下的就变得轻而易举了。
public static string GetOUForUser(string samAccountName)
{
using (var context = new PrincipalContext(ContextType.Domain))
{
using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, 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;
}
}
}
解决方案2后JPBlanc的回答
public static string GetOUForUser(string samAccountName)
{
using (var context = new PrincipalContext(ContextType.Domain))
{
using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, samAccountName))
{
using (DirectoryEntry deUser = user.GetUnderlyingObject() as DirectoryEntry)
{
using (DirectoryEntry deUserContainer = deUser.Parent)
{
return deUserContainer.Properties["Name"].Value.ToString();
}
}
}
}
}
答
好@Empi解决方案的工作,但UserPrincipal
是建立在DirectoryEntry
对象提供parent
或container
性质只是给你你正在寻找的对象,而无需使用字符串方式。
/* 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);
答
这些信息在UserPrincipal.DistinguishedName。您应该检查DistinguishedName是否以“,”+ ou专名(不区分大小写)结尾。但是,您必须知道您要查看的姓名。
例如,如果DN是:CN=Jeff Smith,OU=Sales,DC=Fabrikam,DC=COM
,然后它说,用户在OU=Sales,DC=Fabrikam,DC=COM
OU。
如果对象在其可分辨名称中包含逗号,则不起作用。您需要处理逃脱方式,或使用JPBlanc的解决方案2. – Chalky 2015-09-29 20:17:42