2012-09-26 51 views
4

我一直在試圖編寫一個快速而骯髒的C#.exe,我可以將其發佈給我們IT辦公室中的一些學生工作人員。 .exe應該能夠檢測正在運行的計算機的名稱,在Active Directory中搜索該名稱並禁用計算機條目。到目前爲止,我還沒有遇到名稱檢測或搜索問題,但是當我可以直接進入Active Directory以查看計算機條目未被禁用時,刪除代碼中的一部分給我帶來了誤判。使用C#在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)是與標題中禁用計算機帳戶有關的主題,但評論和代碼似乎都表明這適用於禁用用戶帳戶。

任何有識之士將不勝感激:)

回答

2

你必須保存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,基恩打我吧!

請注意,有時可能需要一段時間才能識別發生了什麼。

+0

太棒了。我感謝幫助,以及冗長。 –

相關問題