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 u开发者_如何转开发sing 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.
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,
The same code above worked. Just add this to Management Class
(@"\\" + serverIP + "\\root\\cimv2:Win32_Service")
精彩评论