views:

2325

answers:

6

I want to write a console or Click Once WinForms app that will programmatically stop and/or start a windows service on a remote box.

Both boxes are running .NET 3.5 - what .NET API's are available to accomplish this?

+2  A: 

You can use System.Management APIs (WMI) to control services remotely. WMI is the generic API to do administrative tasks.

For this problem, however, I suggest you to use the easier to use System.ServiceProcess.ServiceController class.

Mehrdad Afshari
+4  A: 

ServiceController.

You need to have permission to administer the services on the remote box.

As Mehrdad says, you can also use WMI. Both methods work for start and stop, but WMI requires more coding and will give you more access to other resources

StingyJack
+3  A: 

If you don't want to code it yourself, PsService by Microsoft/Sysinternals is a command line tool that does what you want.

sth
+2  A: 

You can also do this from a command console using the sc command:

 sc <server> start [service name]
 sc <server> stop [service name]

Use

sc <server> query | find "SERVICE_NAME"

to get a list of service names.

The option <server> has the form \\ServerName

Example

sc \\MyServer stop schedule will stop the Scheduler service.

Patrick Cuff
+4  A: 

in C#:

var sc = new System.ServiceProcess.ServiceController("MyService", "MyRemoteMachine");
sc.Start();
sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running);
sc.Stop();
sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped);
galets
A: 

if you need to get the name of the Service:

run this from the command line:

sc query

You will see for example, that SQL Server's service name is 'MSSQL$SQLEXPRESS'.

So to stop the SQL Server service in C#:

        ServiceController controller = new ServiceController();
        controller.MachineName = "Machine1";
        controller.ServiceName = "MSSQL$SQLEXPRESS";

        if(controller.Status == ServiceControllerStatus.Running)
            controller.Stop();

        controller.WaitForStatus(ServiceControllerStatus.Stopped);
Sean