查询Active Directory中某个OU下的所有用户,并将用户名输出到列表框中
本文关键字:用户 列表 输出 Directory Active OU 查询 | 更新日期: 2023-09-27 18:02:44
我需要修改我们添加到模式中的自定义属性,但是以所有用户为基础。该属性是MD5散列,我已经将其存储为公共变量。我试图获得指定OU内所有用户的列表,以便在列表框中列出,以便您可以选择所有用户或个人用户,以便将值应用于。
这是我的当前代码Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.DirectoryServices;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
String Password;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Password = textBox1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(Password);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
Password = s.ToString();
textBox2.Text = Password;
}
private void button2_Click(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
如果你使用。net 3.5或更新版本,你可以使用PrincipalSearcher
和"按例查询"原则来进行搜索:
// List of strings for your names
List<string> allUsers = new List<string>();
// create your domain context and define the OU container to search in
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DOMAINNAME",
"OU=SomeOU,dc=YourCompany,dc=com");
// define a "query-by-example" principal - here, we search for a UserPrincipal (user)
UserPrincipal qbeUser = new UserPrincipal(ctx);
// 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.....
allUsers.Add(found.DisplayName);
}
如果你还没有-绝对阅读MSDN文章管理目录安全主体在.NET框架3.5中,它很好地展示了如何充分利用System.DirectoryServices.AccountManagement
的新特性
您可以在UserPrincipal
上指定任何属性,并将其用作PrincipalSearcher
的"按例查询"。