I have this code, which uses WMI to operate on Windows service from C#
code.
When Service.InvokeMethod is called, the method throws an exception:
System.Management Operation is not valid due to the current state of
the object. at System.Management.ManagementObject.InvokeMethod(St ring
methodName, Object[] args)
Here is the method.
RequestStatus is Enum type defined in the class.
ServerName - Machine where the service might be running
ServiceName - Service name on which the operation is to be performed
OpInstructions - Operation to be performed ( StartService,
StopService )
I have tried Start, StartService, RestartService, Stop, StopService.
None have worked.
Services I tried these actions on: Alerter, Messenger, MSSQLSERVER.
Any ideas whats going wrong? Thanks.
public static RequestStatus OperateService ( string ServerName, string
ServiceName, string OpInstructions )
{
ConnectionOptions Options = new
ConnectionOptions();
Options.EnablePrivileges = true;
//Service name space: \root\cimv2
ManagementScope Scope = new
ManagementScope( @"\\" + ServerName + @"\root\cimv2", Options );
Scope.Connect();
if ( Scope.IsConnected )
{
ObjectQuery Query = new
ObjectQuery( "SELECT State FROM Win32_Service WHERE Name = '" +
ServiceName + "'" );
ManagementObjectCollection Services = new ManagementObjectSearcher (
Scope, Query ).Get();
if ( Services.Count > 0
)
{
foreach (
ManagementObject Service in Services )
{
Service.InvokeMethod( OpInstructions, null );
}
return
RequestStatus.Yes;
}
else
{
return
RequestStatus.NotFound;
}
}
return RequestStatus.No;
}