2011-09-26 61 views
2

我想在遠程計算機上重新啓動服務,並且不想使用ServiceController,因爲在下面的ManagementObject在少於2秒內返回時,獲取該計算機上所有服務的進程花費了21秒:使用ManagementObject重新啓動遠程服務

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塊中。我在做什麼?

謝謝 傑克

+0

我有同樣的問題,在任何其他地方得到任何迴應? – apacay

回答

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腳本啓動/停止服務

相關問題