using System.ServiceProcess;
///
/// Control a Windows Service. Note that remote control, would require permission of the current AD
///
public class ServiceControl
{
public static void StopService(string machine, string serviceName)
{
ServiceController controller = getController(machine, serviceName);
if(controller.Status == ServiceControllerStatus.Running)
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped); //xxx - timeout
}
private static ServiceController getController(string machine, string serviceName)
{
ServiceController controller = new ServiceController();
controller.MachineName = machine;
controller.ServiceName = serviceName;
return controller;
}
public static void StartService(string machine, string serviceName)
{
ServiceController controller = getController(machine, serviceName);
if(controller.Status != ServiceControllerStatus.Running)
controller.Start();
controller.WaitForStatus(ServiceControllerStatus.Running); //xxx - timeout
}
}
Note: to get the name of a Service, run this on the command line:
sc query
A load of information will be shown about all the services on the machine. You can read through it, to discover the 'serviceName' of a Service. You can then use the 'serviceName' to control the service, using the source code shown in this post.
Comments
Post a Comment