2

我想在远程机器上重新启动服务并且不想使用 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 块中没有成功。我在做什么?

谢谢杰克

4

1 回答 1

2

I don't know C# but this VBScript sample from here shouldn't be too bad to convert:

' 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

' End of Example WMI script to Start / Stop services

于 2012-09-04T22:30:49.697 回答