2013年6月25日 星期二

用System.DirectoryServices.AccountManagement管理AD帳號

http://www.codeproject.com/Articles/38344/Using-System-DirectoryServices-AccountManagement
根據已上網址資料,改以中文方式簡要說明:

1.System.DirectoryServices.AccountManagement 這是.NET Framework 3.5以後才有的,
.NET Framework 2.0 則是使用 DirectoryEntry,
2者相較,System.DirectoryServices.AccountManagement效能較佳。

2.相關物件說明:
PrincipalContext:與AD的連接物件
Principal:提供AD單元儲存、刪除、新增
GroupPrincipal:由Principal衍生而來,對Group單元做儲存、刪除、新增
UserPricipal:Principal衍生而來,對User單元做儲存、刪除、新增

3.程式範例:
新增帳號
using (var pc = new PrincipalContext(ContextType.Domain,"domain.com", "DC=domain,DC=com"))
{
    using (var up = new UserPrincipal(pc))
    {
        UserPrincipal usr = UserPrincipal.FindByIdentity(pc, "NewUser");
        if (usr != null)
        {
            MessageBox.Show("NewUser,此帳號已經存在!");
            return;
        }
        else
        {
            try
            {
                up.SamAccountName = textBox1.Text;
                up.SetPassword("P@ssw0rd");
                up.Enabled = true;
                //up.PasswordNeverExpires = true;//密碼永久有效
                up.ExpirePasswordNow();//下次登入時更改密碼
                up.Save();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fail!:" + ex);
                Application.Exit();
            }
        }
    }

}

將新增的帳號加入群組
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain.com", DC=com");
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx,"Domain Users");
if (grp != null)
{
    grp.Members.Add(ctx,IdentityType.Name,"NewUser");
    grp.Save();
    grp.Dispose();
}
ctx.Dispose();

沒有留言: