[英]Use C# to disable a computer in Active Directory
我一直在努力寫一個快速而骯臟的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)是一個與禁用標題中的計算機帳戶,但評論和代碼似乎都表明這適用於禁用用戶帳戶。
任何見解將不勝感激:)
您需要在ComputerPrincipal
對象上調用Save
:
您必須保存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打敗了我!
請注意,有時可能需要一段時間才能識別發生的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.