how to access romote windows service with Related ObjectQuery

1k views Asked by At

I want to control (start and stop) a windows service which is in the remote machine. I can connect that machine but I can't access to windows service. Here is my code. Can you help me?

    ConnectionOptions oConn = new ConnectionOptions();
    oConn.Username = "****";
    oConn.Password = "****";

    ManagementScope managementScope = new ManagementScope(@"\\***.***.***.***\root\CIMV2", oConn);
    managementScope.Connect();

  RelatedObjectQuery roq = new RelatedObjectQuery("Win32_Service.Name='KanAktarim'");
  ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(managementScope, roq);
  ManagementObjectCollection mbCollection = moSearcher.Get();
1

There are 1 answers

0
cagin On BEST ANSWER
            ManagementObjectSearcher moSearcher = new ManagementObjectSearcher();
            moSearcher.Scope = managementScope;
            moSearcher.Query = new ObjectQuery("SELECT * FROM win32_Service WHERE Name ='KanAktarim'");
            ManagementObjectCollection mbCollection = moSearcher.Get();

            foreach (ManagementObject oReturn in mbCollection)
            {
                ManagementBaseObject outParams = oReturn.InvokeMethod("StartService", null, null);
                ManagementBaseObject outParams = oReturn.InvokeMethod("StopService", null, null);
                string a = outParams["ReturnValue"].ToString();

                string state = oReturn.Properties["State"].Value.ToString().Trim();
            }