tags:

views:

1272

answers:

3

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.

+1  A: 

You can use wmi for this (System.Management). You can also use ServiceController.GetServices().

Arnshea
+4  A: 

ServiceController.GetServices("machineName") returns an array of ServiceController objects for a particular machine.

This:

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();
        }
    }
}

produces:

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...

Of course, I used the parameterless version to get the services on my machine.

Aaron Daniels
+2  A: 

To use the ServiceController method I'd check out the solution with impersonation implemented in this previous question: http://stackoverflow.com/questions/210296/net-2-0-servicecontroller-getservices/212673#212673

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

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 searcher.Get())
    {
        Console.WriteLine(mo.GetText(TextFormat.Mof));
    }
}
xcud
Thank you. All answers helped point me to WMI and System.Management. I liked the query and used this snippet.thx again.-k2
k2