【问题标题】:Use ManagementObject to restart remote service使用 ManagementObject 重启远程服务
【发布时间】:2011-09-26 02:19:29
【问题描述】:

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

谢谢 杰克

【问题讨论】:

  • 我也有同样的问题,其他地方有回复吗?

标签: c# service wmi restart system.management


【解决方案1】:

我不懂 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 脚本结束

【讨论】:

    猜你喜欢
    • 2013-08-26
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    相关资源
    最近更新 更多