Check status of services that run in a remote computer using C#

Krish picture Krish · Aug 26, 2009 · Viewed 36.3k times · Source

I'm using the following code.

ServiceController MyController = new ServiceController();
MyController.MachineName = server_txt.Text.Trim();
MyController.ServiceName = "Service1";

string msg = MyController.Status.ToString();
Label1.Text = msg;

This code works fine for network computers where I have access. How to change this so it works for the systems in different domains using credentials?

Answer

user797717 picture user797717 · Jun 14, 2011

If you use WMI, you can set the credentials in 'ConnectionOptions'.

ConnectionOptions op = new ConnectionOptions();
op.Username = "Domain\\Domainuser";
op.Password = "password";
ManagementScope scope = new ManagementScope(@"\\Servername.Domain\root\cimv2", op);
scope.Connect();
ManagementPath path = new ManagementPath("Win32_Service");
ManagementClass services;
services = new ManagementClass(scope, path, null);

foreach (ManagementObject service in services.GetInstances())
{

if (service.GetPropertyValue("State").ToString().ToLower().Equals("running"))
{ // Do something }

}