我一直在尝试编写一个快速而肮脏的 C# .exe,我可以将它分发给我们 IT 办公室的一些学生工作者。.exe 应该能够检测到运行它的机器的名称,在 Active Directory 中搜索该名称,然后禁用计算机条目。到目前为止,我在名称检测或搜索方面没有遇到任何问题,但是当我可以直接进入 Active Directory 以查看计算机条目未被禁用时,删除代码位给了我一个误报。
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;
}
}
}
这是我现在拥有的代码;前面的代码是关于让用户根据检测到的计算机名称检查计算机名称并确认他们确实想要禁用计算机帐户。一旦他们点击确认(目前被误导为确认删除按钮),它应该运行此代码以报告成功或失败。但是,在测试中,它报告成功,尽管我可以看到计算机对象没有被禁用。
此链接(http://stackoverflow.com/questions/591681/using-c-how-do-you-check-if-a-computer-account-is-disabled-in-active-directory)是一个与在标题中禁用计算机帐户,但评论和代码似乎都表明这适用于禁用用户帐户。
任何见解将不胜感激:)