使用C#禁用Active Directory中的计算机
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用C#禁用Active Directory中的计算机,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2689字,纯文字阅读大概需要4分钟。
内容图文
![使用C#禁用Active Directory中的计算机](/upload/InfoBanner/zyjiaocheng/803/c22e992390ef4a59b6b5f7146b617b7e.jpg)
我一直在努力写一个快速而肮脏的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;
}
}
}
这是我现在的代码;上述代码是让用户根据检测到的计算机名检查计算机名称,并确认他们确实要禁用该计算机帐户.一旦他们点击确认这一点(误导性地当前标记为确认删除按钮),它应运行此代码以报告成功或失败.但是,在测试中,它会报告成功,但我可以看到计算机对象未被禁用.
此链接(https://stackoverflow.com/questions/591681/using-c-how-do-you-check-if-a-computer-account-is-disabled-in-active-directory)是一个与禁用标题中的计算机帐户,但评论和代码似乎都表明这适用于禁用用户帐户.
任何见解将不胜感激:)
解决方法:
您必须保存PrincipalComputer对象.否则你的代码很好.这是一个简单的控制台应用程序版本,如果计算机不存在,将不返回任何内容.
static void Main(string[] args)
{
Console.WriteLine("Enter the name of the computer you wish to disable");
string ComputerName = Console.ReadLine();
if (ComputerName != "" && ComputerName != null)
{
using (PrincipalContext TargetDomain = new PrincipalContext(ContextType.Domain, null, "admin", "password"))
{
ComputerPrincipal TargetComputer = ComputerPrincipal.FindByIdentity(TargetDomain, ComputerName);
if (TargetComputer != null)
{
if ((bool)TargetComputer.Enabled)
{
Console.WriteLine("Computer is currently enabled, it will now be disabled");
TargetComputer.Enabled = false;
Console.WriteLine("Is computer now enabled? " + TargetComputer.Enabled);
TargetComputer.Save();
}
else
{
Console.WriteLine("Computer is currently disabled, it will now be enabled");
TargetComputer.Enabled = true;
Console.WriteLine("Is computer now enabled? " + TargetComputer.Enabled);
TargetComputer.Save();
}
Console.Read();
}
}
}
}
dang,Kieren打败了我!
请注意,有时可能需要一段时间才能识别发生的事情.
内容总结
以上是互联网集市为您收集整理的使用C#禁用Active Directory中的计算机全部内容,希望文章能够帮你解决使用C#禁用Active Directory中的计算机所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。