Tôi muốn kiểm tra xem liệu người dùng có thuộc một OU mẹ cụ thể không.Nhận cấp độ gốc của người dùng trong Active Directory bằng C#
Tôi có thể làm như thế nào?
Kiểm tra mã bên dưới để biết rõ ràng về những gì tôi đang tìm kiếm.
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);
}
Domain:
- Quốc OU
- tạo ảnh vui nhộn OU
- Joe
- Dù OU
- Mike
- tạo ảnh vui nhộn OU
Giải pháp 1 sau câu trả lời empi của
Với những thông tin được đưa ra bởi empi, tôi đã viết các phương pháp dưới đây để trích xuất các OU đầu tiên trong DistinguishedName. Sau khi làm điều đó, phần còn lại thật dễ dàng.
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;
}
}
}
Giải pháp 2 sau câu trả lời JPBlanc của
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();
}
}
}
}
}
Không hoạt động nếu các đối tượng có dấu phẩy trong tên phân biệt của chúng. Bạn cần phải xử lý cách những người đang trốn thoát, hoặc sử dụng giải pháp JPBlanc 2. – Chalky