Stop / start the service or close the process / maintenance of the sql server on the remote computer

I am trying to shut down and start the sql server on a remote computer (on the same network), I used this code

ConnectionOptions options = new ConnectionOptions(); options.Username = userName; options.Password = password; ManagementScope scope = new ManagementScope( string.Format(@"\\{0}\root\cimv2", serverFullName), options); scope.Connect(); ObjectQuery query = new ObjectQuery( string.Format(@"SELECT * FROM Win32_Process WHERE Name='{0}'", processToTerminate)); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); ManagementObjectCollection queryCollection = searcher.Get(); foreach (ManagementObject m in queryCollection) { m.InvokeMethod("Terminate", null); } 
  • Is there any other way to do this?
  • How can I start a process (if Terminate closes it)?

thanks

+4
source share
4 answers

What about using the ServiceController class? (see MSDN )

 // just replace the params with your values ServiceController sc = new ServiceController("SERVICENAME", "MACHINENAME"); if (sc.Status.Equals(ServiceControllerStatus.Running)) sc.Stop(); 

That should do the trick.

Hth

+5
source

It would seem much simpler to just use the ServiceController class, which you can give the service name and computer name , and then call methods like Start and Stop .

+4
source

Killing a process and stopping a service are two different things. A service may spawn other processes that will remain protracted. In addition, you effectively pull out the plug in the process. This does not give time to stop the grace, write everything to disk, etc.

Instead, you should use the Win32_Service WMI object to find your service. This is the StartService and StopService , which will allow you to stop and start it as needed.

Remember that this WMI object refers to services, not processes, so you will have to configure your code to stop it by the service name, not the process name. Something like that:

 ConnectionOptions options = new ConnectionOptions(); options.Username = userName; options.Password = password; ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", serverFullName), options); scope.Connect(); ObjectQuery query = new ObjectQuery(string.Format(@"SELECT * FROM Win32_Service WHERE Name='{0}'",serviceToStop)); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); ManagementObjectCollection queryCollection = searcher.Get(); foreach (ManagementObject m in queryCollection) { m.InvokeMethod("StopService", null); } 

Then you can use InvokeMethod in the StartService.

+3
source

you can do something like this to start and stop your sql server

 System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = "net start \"Sql Server (SQLEXPRESS)\""; process.Start(); 
0
source

Source: https://habr.com/ru/post/1386930/


All Articles