In C# how do i query the list of running services on a windows server?

前端 未结 4 1535
我寻月下人不归
我寻月下人不归 2020-12-14 01:45

I want to query for a list of services running as a specific user on a remote machine and then check the health of each. I\'m building a custom console.

4条回答
  •  -上瘾入骨i
    2020-12-14 01:53

    To use the ServiceController method I'd check out the solution with impersonation implemented in this previous question: .Net 2.0 ServiceController.GetServices()

    FWIW, here's C#/WMI way with explicit host, username, password:

    using System.Management;
    
    static void EnumServices(string host, string username, string password)
    {
        string ns = @"root\cimv2";
        string query = "select * from Win32_Service";
    
        ConnectionOptions options = new ConnectionOptions();
        if (!string.IsNullOrEmpty(username))
        {
            options.Username = username;
            options.Password = password;
        }
    
        ManagementScope scope = 
            new ManagementScope(string.Format(@"\\{0}\{1}", host, ns), options);
        scope.Connect();
    
        ManagementObjectSearcher searcher = 
            new ManagementObjectSearcher(scope, new ObjectQuery(query));
        ManagementObjectCollection retObjectCollection = searcher.Get();
        foreach (ManagementObject mo in retObjectCollection)
        {
            Console.WriteLine(mo.GetText(TextFormat.Mof));
        }
    }
    

提交回复
热议问题