在C#中我如何查询Windows服务器上正在运行的服务列表?

kke*_*y18 25 c# windows

我想查询在远程计算机上作为特定用户运行的服务列表,然后检查每个服务的运行状况.我正在构建一个自定义控制台.

Aar*_*els 40

ServiceController.GetServices("machineName")返回ServiceController特定计算机的对象数组.

这个:

namespace AtYourService
{
    using System;
    using System.ServiceProcess;

    class Program
    {
        static void Main(string[] args)
        {
            ServiceController[] services = ServiceController.GetServices();

            foreach (ServiceController service in services)
            {
                Console.WriteLine(
                    "The {0} service is currently {1}.",
                    service.DisplayName,
                    service.Status);
            }

            Console.Read();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

生产:

The Application Experience service is currently Running.

The Andrea ST Filters Service service is currently Running.

The Application Layer Gateway Service service is currently Stopped.

The Application Information service is currently Running.

etc...
Run Code Online (Sandbox Code Playgroud)

当然,我使用无参数版本来获取我的机器上的服务.


xcu*_*cud 24

要使用ServiceController方法,我将查看在上一个问题中实现模拟的解决方案: .Net 2.0 ServiceController.GetServices()

FWIW,这是带有显式主机,用户名和密码的C#/ WMI方式:

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));
    }
}
Run Code Online (Sandbox Code Playgroud)


Arn*_*hea 5

你可以使用wmi(System.Management).你也可以使用ServiceController.GetServices().