公司的组织结构经常发生变化,而我们的域帐户信息( AD )是和真实的组织机构相对应的。组织机构变化了,我们自然要改动相应的域帐户信息啦。这是一件很痛苦的事情,原因是什么,大家都明白。那么能不能用程序来解决这个问题呢?( windows2003 的管理工具好像已经支持批量修改域帐户信息了)。
我创建了一个 windows 应用程序来解决:
在 Form 上放置了六个 comboBox 用于选择公司的 OU (可以选择五级 OU ,如果你喜欢可以用 TreeView 更好些)。
加载 Form 的时候初始化这些 comboBox :
private void Form1_Load(object sender, System.EventArgs e)
{
//初始化公司选择框
DirectoryEntry de1=new DirectoryEntry();
de1.Path="LDAP://DC= test ,DC=net";
try
{
// 所有 OU (第一级)
foreach (DirectoryEntry ch1 in de1.Children)
{
str=ch1.Name.ToString();
string str1="";
//str1=str.Substring(0,str.IndexOf("="));
str1=ch1.SchemaClassName.ToString();
if (str1=="organizationalUnit")
{
//listBox1.Items.Add(ch1.Name.ToString());
// 加入第一个 combobox
comboBox1.Items.Add(ch1.Name.ToString());
//
comboBox3.Items.Add(ch1.Name.ToString());
}
}
de1.Close();
//textBox1.Text=textBox1.Text+"--------------next------------------------\r\n";
//
MessageBox.Show("finish!!!");
}
catch(Exception ex)
{
strErr=ex.Message;
}
finally
{}
}
在初始化 form 的时候在第一个 combobox 中显示出所有的第一层 OU 。然后,在选择了这个 combobox 的时候,在第二个 combobox 中显示下一级 OU :
private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
//str=listBox1.SelectedItem.ToString();
str=comboBox1.SelectedItem.ToString();
DirectoryEntry de1=new DirectoryEntry();
de1.Path="LDAP://"+str+",DC= test ,DC=net";
try
{
comboBox2.Items.Clear();
comboBox2.Text="";
comboBox2.Refresh();
foreach (DirectoryEntry ch1 in de1.Children)
{
//
textBox1.Text=textBox1.Text+str+"\r\n";//ch.Properties["adpath"][0].ToString();
string str1="";
str1=ch1.SchemaClassName.ToString();
if (str1=="organizationalUnit")
{
comboBox2.Items.Add(ch1.Name.ToString());
}
}
de1.Close();
//textBox1.Text=textBox1.Text+"--------------next------------------------\r\n";
//
MessageBox.Show("finish!!!");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{}
}
依次在下一个 combobox 中显示下一级 OU 。选择好要修改的 OU 下后,就可以修改该 ou 下所有的信息了。这里以修改部门名称为例。
使用一个 Textbox 输入部门名称,放一个按钮触发修改动作:
private void button1_Click(object sender, System.EventArgs e)
{
string strADRoot="";
string strName="";
//str 中保存的是 OU 的 ADPath 的一部分,即通过选择 combobox 产生的字符串,类似于 ou =imd,OU=company
strADRoot="LDAP://"+str+",DC= test ,DC=net";
DirectoryEntry de=new DirectoryEntry();
de.Path=strADRoot;
// 修改所有的 user 对象
foreach(DirectoryEntry chm in de.Children)
{
string strType="";
strType=chm.SchemaClassName.ToString();
if(strType.ToUpper()=="USER")
{
strName=chm.Name.ToString();
// 判断是否属性值是否为空
if(chm.Properties.Contains("department"))
{
chm.Properties["department"][0]=textBox2.Text.ToString();
chm.CommitChanges();
textBox3.Text=textBox3.Text+chm.Name .ToString()+"的部门名称修改成功!\r\n";
}
else
{
chm.Properties["department"].Add(textBox2.Text.ToString());
chm.CommitChanges();
//textBox3.Text=textBox3.Text+ch1.Name .ToString()+"\r\n";
textBox3.Text=textBox3.Text+chm.Name .ToString()+"的部门名称添加成功!\r\n";
}
}
}