停止/启动服务或关闭远程计算机上的sql server进程/服务

时间:2011-12-18 16:06:20

标签: c# process windows-services remote-access

我试图在远程计算机上(在同一网络上)关闭并启动sql server,我已经使用了这段代码

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. 还有另一种方法吗?
  2. 我如何开始这个过程(如果终止关闭它)?
  3. 谢谢

4 个答案:

答案 0 :(得分:5)

使用 ServiceController 类怎么样? (见MSDN

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

这应该可以解决问题。

HTH

答案 1 :(得分:4)

似乎很多更容易使用ServiceController类,您可以给service name and computer name,然后调用Start等方法和Stop

答案 2 :(得分:3)

杀死进程并停止服务是两回事。服务可能会产生其他仍然会延迟的进程。此外,您正在有效地拉动该过程的插头。它没有给予任何时间优雅地停止,将所有内容写入磁盘等等。

相反,您应该使用Win32_Service WMI对象来查找您的服务。这有一个StartServiceStopService方法,可让您根据需要停止并启动它。

请注意,此WMI对象是关于 services ,而不是进程,因此您必须调整代码以通过服务名称而不是进程名称来停止它。像这样:

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

稍后您可以在StartService上使用InvokeMethod

答案 3 :(得分:0)

你可以这样做来启动和停止你的SQL Server

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