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

私は C# を知りませんが、ここからのこの 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 スクリプトの例の終わり

于 2012-09-04T22:30:49.697 に答える