C# Query Windows Service

折月煮酒 提交于 2019-12-06 05:51:35

问题


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.


回答1:


The information you're looking for is available in WMI.

It will be MUCH easier to write this whole thing in PowerShell than in Pure C#. WMI code gets very messy in C# (or C++, or VBScript), very quickly. This snippet demostrates getting the data from a list of computers. To embed in C#, simply use System.Management.Automation, and add PowerShell.Create().AddScript(...).Invoke()

$computerList = "a","b","c"
Get-WmiObject -computerName $computerList -asjob
    | Wait-job
    | receive-job
    | Select-Object DisplayName, Description, StartMode, State

Hope this helps,




回答2:


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

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


来源:https://stackoverflow.com/questions/6711726/c-sharp-query-windows-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!