How can I programmatically stop/start a windows service on a remote box?

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?


Solution 1:

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);

Solution 2:

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.

Solution 3:

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

Solution 4:

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

Solution 5:

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.