Search code examples
c#servicewmi

WMI MangementObject.InvokeMethod()


I'm trying to debug a section of code, which updates the crednetials used for a Windows service, which is not functioning. It doesn't throw an exception, it just doesn't pass the check to show that it was applied.

The MSDN describes the constructor as follows:

public Object InvokeMethod(
    string methodName,
    Object[] args
)

What I don't understand is where it looks for the methodName string which you pass in. My assumption was it would look in the code for the Service I am trying to update. However there is no Change method present in the service the code attempts to update.

This CodeProject tutorial also seems to indicate that there is a list of valid arguments for the methodName as it uses "create" and "delete" which aren't present in it's source code.

String serviceName = "Scan Data Service";

using (ManagementObject service = new ManagementObject(new ManagementPath("Win32_Service.Name='" + serviceName + "'")))
{
    Object[] wmiParams = new Object[11];
    if (arguments == null)
    {
        wmiParams[6] = "LocalSystem";
        wmiParams[7] = "";
    }
    else
    {
        wmiParams[6] = arguments[0]; //Username
        wmiParams[7] = arguments[1]; //Password
    }
    service.InvokeMethod("Change", wmiParams);
}
SelectQuery query = new SelectQuery("select startname from Win32_Service where name = '" + serviceName + "'");

bool updated = false;

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
    foreach (ManagementObject service in searcher.Get())
    {
        String startName = service["startname"].ToString();

        if ((String.Compare(startName, "LocalSystem", true) == 0 && arguments == null) ||
            (arguments != null && String.Compare(startName, arguments[0], true) == 0))
        {
            updated = true;
        }
    }
}

Is there a list of methodName arguments for InvokeMethod() somewhere which are valid for all services? Or is there supposed to be something implemented in my Service code which has to be somehow read or reflected?


Solution

  • Resolved.

    It depends what you're doing with WMI, as I was working with services it utilised the Win32_Service Class the method names it was targeting belong to this.

    There are of course many more Win32 Classes you can utilise methods from for different tasks.