I’ve been trying to write a quick and dirty C# .exe that I can distribute to some student workers in our IT office. The .exe should be able to detect the name of the machine on which it’s being run, search for that name in Active Directory, and disable the computer entry. So far I haven’t had a problem with the name detection or search, but the bit of removal code is giving me a false positive when I can go directly into Active Directory to see that the computer entry has not been disabled.
private void confirmRemoveButton_Click(object sender, EventArgs e)
{
string computerName = Environment.MachineName;
using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, null, "useraccount", "password"))
{
ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(domainContext, computerName);
if (computer != null)
{
try
{
computer.Enabled = false;
label3.Visible = true;
label3.Text = "Computer was disabled in Active Directory.";
button1.Visible = true;
}
catch (Exception x)
{
label3.Visible = true;
label3.Text = "Unable to disable computer with exception " + x;
button1.Visible = true;
}
}
else if (computer == null)
{
label3.Visible = true;
label3.Text = "Computer was not found in Active Directory.";
button1.Visible = true;
}
else
{
label3.Visible = true;
label3.Text = "Unexpected error in computer search.";
button1.Visible = true;
}
}
}
This is the code I have right now; the preceding code is about having the user check the computer name against the detected computer name and confirm that they actually want to disable the computer account. Once they click to confirm this (misleadingly currently labeled as confirm removal button), it should run this code to report success or failure. However, in testing, it reports success though I can see the computer object is not disabled.
This link (http://stackoverflow.com/questions/591681/using-c-how-do-you-check-if-a-computer-account-is-disabled-in-active-directory) is a topic relating to disabling a computer account in the title, but the comments and code all seem to suggest that this applies to disabling a user account.
Any insight would be appreciated 🙂
You have to save the PrincipalComputer object. Otherwise your code is fine. Here’s a simple console app version which will return nothing if the computer doesn’t exist.
dang, Kieren beat me to it!
Note, sometimes it can take awhile before AD recognizes what has happened.