Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

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

20 views
Skip to first unread message

Zeya

unread,
Oct 6, 2005, 8:22:10 PM10/6/05
to
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;

}

Zeya

unread,
Oct 7, 2005, 10:06:28 PM10/7/05
to
Found the problem. My WQL query was wrong. It needed Name.

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

0 new messages