Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to delete computer account from Active Directory using c#

Is there any sample that deletes computer account from AD using C#?

I have searched many sources, but all are about user account.

added my code here, i always got errors for some reason.

public static bool checkExistingPC(string compName,string userName,string userPwd )
{
    try
    {
        DirectoryEntry entry = new DirectoryEntry("LDAP://test.com",userName,userPwd,AuthenticationTypes.Secure);
        DirectorySearcher mySearcher = new DirectorySearcher(entry);
       mySearcher.Filter = "(&(objectClass=computer)(|(cn=" + compName + ")(dn=" + compName + ")))";
       foreach (SearchResult result in mySearcher.FindAll())
       {
           if (result != null)
           {

               MessageBox.Show("computer GetDirectoryEntry():" + result.Path+"\n"+"computer path: "+result.Path);
                DirectoryEntry entryToRemove = new DirectoryEntry(result.Path,userName,userPwd);
                 entry.Children.Remove(entryToRemove);

               return true;
           }
           else
           {
               return false;
           }
       }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }
    return false;
}
like image 519
ikel Avatar asked Sep 02 '25 14:09

ikel


1 Answers

If you're on .NET 3.5 and up (if you're not - time to upgrade!), you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

  • Managing Directory Security Principals in the .NET Framework 3.5
  • MSDN docs on System.DirectoryServices.AccountManagement

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find the computer in question
ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(ctx, "NAME");

// if found - delete it
if (computer != null)
{
   computer.Delete();
}

The new S.DS.AM makes it really easy to play around with users, computers and groups in AD!

like image 184
marc_s Avatar answered Sep 05 '25 03:09

marc_s