在远程计算机上停止/启动服务或关闭SQL Server进程/服务。

4

我正在尝试关闭和启动位于同一网络上的远程计算机上的SQL服务器,我已经使用了以下代码:

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. 如果终止了进程,我该如何启动它?

谢谢

4个回答

5

使用 ServiceController 类如何?(参见 MSDN

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

这应该能解决问题。

希望对你有所帮助。


4

使用ServiceController类似乎更容易,您可以向其提供服务名称和计算机名称,然后调用StartStop等方法。


我也想说同样的话,但我似乎找不到有关指定连接到远程系统凭据的任何信息(就像 OP 使用 WMI 一样)。还是我错过了什么? - vcsjones
@vcsjones - 确实,在他们的示例中,他们指定了凭据。不清楚这是否是解决方案的必需部分,还是当前代码的产物(例如,如果从其他地方复制)。故事中没有提到,但我正在四处寻找是否可能。 - Damien_The_Unbeliever
这是我的问题,我如何为远程计算机提供其凭据? - guyl
@guyl - 这个问题似乎有一个用VB.Net编写的帮助类来建立凭据 - 看起来很容易翻译成C#。它有一些P / Invoke代码,所以选择你喜欢的方式 - 这个或WMI。 - Damien_The_Unbeliever

3
终止进程和停止服务是两个不同的操作。服务可能会生成其他进程,这些进程将继续运行。此外,您实际上是拔掉了进程的插头。它没有被赋予任何时间以优雅地停止、将所有内容写入磁盘等。
相反,您应该使用 Win32_Service WMI 对象来查找您的服务。这个对象有一个 StartServiceStopService 方法,允许您根据需要停止和启动服务。
请注意,这个 WMI 对象是关于服务的,而不是进程,所以您需要调整您的代码以通过服务名称而不是进程名称来停止它。例如:
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。

0

你可以像这样启动和停止你的SQL服务器

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接