Windows service operation throws error: Operation is not valid due to the current state of the objec

Z

Zeya

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(String
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;



}
 
Z

Zeya

Found the problem. My WQL query was wrong. It needed Name.

SELECT State, Name FROM Win32_Service WHERE Name = '" +
ServiceName + "'"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top