Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stop / start service or close the sql server process / service on a remote computer

I am trying to shutdown and start the sql server on a remote computer (on the same network), i have 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);
}
  1. is there another way of doing that ?
  2. how can i start the process (if Terminate close it)?

Thank you

like image 907
guyl Avatar asked Dec 16 '22 06:12

guyl


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

This should do the trick.

hth

like image 132
Pilgerstorfer Franz Avatar answered Dec 18 '22 20:12

Pilgerstorfer Franz