使用ManagementObject重新启动远程服务

时间:2011-09-26 02:19:30

标签: c# service wmi restart system.management

我想在远程计算机上重新启动服务,并且不想使用ServiceController,因为获取该计算机上所有服务的过程需要21秒,而以下ManagementObject在不到2秒的时间内返回:

  ConnectionOptions options = new ConnectionOptions();
  ManagementScope scope = new ManagementScope("\\\\" + ConfigurationManager.AppSettings["remoteMachine"] + "\\root\\cimv2", options);
  scope.Connect();
  ObjectQuery query = new ObjectQuery("Select * from Win32_Service where DisplayName LIKE '%" + ConfigurationManager.AppSettings["likeSerices"] + "%'");
  ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
  ManagementObjectCollection queryCollection = searcher.Get();

  List<ServiceObj> outList = new List<ServiceObj>();
  foreach (ManagementObject m in queryCollection)
  {
    ServiceObj thisObject = new ServiceObj();
    thisObject.DisplayName = m["DisplayName"].ToString();
    thisObject.Name = m["Name"].ToString();
    thisObject.Status = m["State"].ToString();
    thisObject.StartMode = m["StartMode"].ToString();
    outList.Add(thisObject);
  }

我现在尝试过:m.InvokeMethod(“StopService”,null);在foreach区块没有成功。我在做什么?

谢谢 千斤顶

1 个答案:

答案 0 :(得分:2)

我不知道C#但来自here的这个VBScript样本不应该太糟糕转换:

' VBScript Restart Service.vbs
' Sample script to Stop or Start a Service
' www.computerperformance.co.uk/
' Created by Guy Thomas December 2010 Version 2.4
' -------------------------------------------------------'
Option Explicit
Dim objWMIService, objItem, objService
Dim colListOfServices, strComputer, strService, intSleep
strComputer = "."
intSleep = 15000
WScript.Echo " Click OK, then wait " & intSleep & " milliseconds"

'On Error Resume Next
' NB strService is case sensitive.
strService = " 'Alerter' "
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
("Select * from Win32_Service Where Name ="_
& strService & " ")
For Each objService in colListOfServices
objService.StopService()
WSCript.Sleep intSleep
objService.StartService()
Next
WScript.Echo "Your "& strService & " service has Started"
WScript.Quit

'启动/停止服务的示例WMI脚本结束