Reputation: 3113
I want to restart a service on a remote machine and do not want to use ServiceController because the process to get all services on that machine took 21 seconds while the following ManagementObject returned in less than 2 seconds:
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);
}
I now tried:m.InvokeMethod("StopService", null); in the foreach block with no success. What am I doing worng?
Thank you Jack
Upvotes: 2
Views: 2140
Reputation: 1470
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
Upvotes: 2