Search code examples
c#windows-servicesservicecontroller

C# Query Windows Service


I have been using an application that queries Windows Services running on remote servers and writes the Machine Name, Service Name, and Status to a database.

However, I want to try and capture the startup type (Automatic, Manual, Disabled) as well. I was using a Service Controller which does not have any options for startup type so I started looking at using a Management Class. This class looks like it has everything I need but I don't know how to use it against my remotes servers. For the Service Controller, I was doing this:

ServiceController[] services = ServiceController.GetServices(serverIP);

foreach (ServiceController service in services)
{
   var machine = service.MachineName;
   var displayName = service.DisplayName;
   var status = service.Status;
}

I tried this for the Management class:

ManagementClass class1 = new ManagementClass(serverIP + "\\" + "Win32_Service");

foreach (ManagementObject ob in class1.GetInstances())
{
   var machine = serverIP;
   var displayName = ob.GetPropertyValue("Description");
   var name = ob.GetPropertyValue("PathName");
   var startMode = ob.GetPropertyValue("StartMode");
   var status = ob.GetPropertyValue("State");
}

But of course it didn't work. Anyone know how I can get the Services from a remote machine using the Management Class? Or is there another way using the Service Controller to get the startup type?

I also tried to combine them both and put the Management Class foreach statement inside the Service Controller but it got stuck in an endless loop.


Solution

  • The same code above worked. Just add this to Management Class

    (@"\\" + serverIP + "\\root\\cimv2:Win32_Service")