使用C#批量修改域帳戶信息
2024-07-21 02:19:02
供稿:網友
公司的組織結構經常發生變化,而我們的域帳戶信息(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";
}
}
}