2013-03-04 91 views
1

嗨我想要使用C#獲取遠程計算機上的所有服務及其「登錄AS」列表(在網絡中使用計算機名或IP)。獲取遠程機器上運行的服務的登錄

我認爲可以使用WMI來實現,但不知道如何(我之前沒有使用過wmi)?

請幫助。

回答

1

您可以使用Win32_Service類的StartName屬性。

試試這個樣本

using System; 
using System.Collections.Generic; 
using System.Management; 
using System.Text; 

namespace GetWMI_Info 
{ 
    class Program 
    { 

     static void Main(string[] args) 
     { 
      try 
      { 
       string ComputerName = "localhost"; 
       ManagementScope Scope;     

       if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) 
       { 
        ConnectionOptions Conn = new ConnectionOptions(); 
        Conn.Username = ""; 
        Conn.Password = ""; 
        Conn.Authority = "ntlmdomain:DOMAIN"; 
        Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn); 
       } 
       else 
        Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null); 

       Scope.Connect(); 
       ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_Service"); 
       ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query); 

       foreach (ManagementObject WmiObject in Searcher.Get()) 
       { 
        Console.WriteLine("{0,-35} {1,-40}","Name",WmiObject["Name"]);// String 
        Console.WriteLine("{0,-35} {1,-40}","StartName",WmiObject["StartName"]);// String 

       } 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine(String.Format("Exception {0} Trace {1}",e.Message,e.StackTrace)); 
      } 
      Console.WriteLine("Press Enter to exit"); 
      Console.Read(); 
     } 
    } 
} 
+0

這可以在不使用WMI的情況下實現嗎? – mry 2013-03-06 06:05:01

+0

是的,您可以嘗試使用[ServiceController](http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx)類 – RRUZ 2013-03-06 15:11:13

+0

我做過,但它不會「以「或者我找不到。你能幫我解決嗎? – mry 2013-03-07 11:04:26

0

我覺得有更簡單的方法,你可以找到它在服務細節註冊表(系統\ CurrentControlSet \服務\服務名) 和你有對象名稱