簡體   English   中英

如何使用 PrincipalContext 刪除 OU

[英]How can I delete OU with PrincipalContext

我需要創建一個 gui,其中除其他要求外,還需要刪除全局組和組織單位。 我有刪除工作組的功能,但我也需要能夠刪除 OU。

我對組使用此代碼:

 private void btn_verwijderGG_Click(object sender, EventArgs e)
    {
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
        GroupPrincipal ou = GroupPrincipal.FindByIdentity(ctx, txt_OUNaam.Text);

        if (ou != null)
        {
            ou.Delete();
            MessageBox.Show("OU" + txt_OUNaam.Text + "is verwijderd");

        }
        else
        {
            MessageBox.Show("OU niet gevonden");
        }
    }

但是如何將 te GroupPrincipal 更改為 ou? 或者我需要做什么才能做到這一點?

這是我過去用來刪除 OU 的代碼(但請謹慎使用

  1. 使用根作為 SearchBase ... 查看某個父 OU 下
  2. 使用 DirectorySearcher 搜索與過濾器匹配的所有 OU
  3. 遍歷結果並刪除它們。
  4. 確保您有權刪除 OU,並且該 OU 沒有打開“防止意外保護”。
    public void DeleteOU (string ldap, string filterOU)
    {
        // ldap = "LDAP://DC=fabri,DC=com"
        // filteredOU = "OU=OUName" or "CN=OUName" depending on how its configured.

        DirectoryEntry root = new DirectoryEntry(ldap);
        DirectorySearcher searcher = new DirectorySearcher(root);
        searcher.Filter = $"(&(objectCategory=organizationalUnit)({filterOU}))";

        try
        {
            foreach (SearchResult res in searcher.FindAll())
            {
                DirectoryEntry thisOU = res.GetDirectoryEntry();
                thisOU.DeleteTree();
                thisOU.CommitChanges();
            }
        }
        catch (Exception ex)
        {
            // do something with exception. Most likely, Not Found.
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM