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?
-
You can use
System.ManagementAPIs (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.ServiceControllerclass. -
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
-
If you don't want to code it yourself, PsService by Microsoft/Sysinternals is a command line tool that does what you want.
-
You can also do this from a command console using the
sccommand: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\\ServerNameExample
sc \\MyServer stop schedulewill stop the Scheduler service. -
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); -
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);
0 comments:
Post a Comment