Stop a windows service on a remote machine

Hello,

I have to create  an application on my machine(A) to start/stop a Windows service on another machine(B)  connected through network.

I have used the System.ServiceProcess.ServiceController object. It provides two properties to specify the 'machine name' & 'service name'.

But when I use the ServcieController object's "stop" method, I get an error indicating that I don't have the permission to do stop a service on the machne(B).

My questions:
"In case, I do know the administrator login & password of machine(B), how can I enter those credentials and stop the service on machine(B) through machine(A) "

Also,  "How do I circumvent this problem
          "Is there any way, by which I can establish my user credentials on the remote machine and then toggle with the Windows service "

Any help will be most welcome.

Thank you.





Answer this question

Stop a windows service on a remote machine

  • Rakosnicek

    This is sample code that uses the System.Management classes:

     public void RemoteService()
    {
     ConnectionOptions coptions = new ConnectionOptions();
     coptions.Username = "Administrator";
     coptions.Password = "whatever";
     string servername = "someserver";
     string themethod = "StopService";
     string servicename = "MSIserver"; // Just a test on the MSI Service
     InvokeMethodOptions options = new InvokeMethodOptions();
     options.Timeout = new TimeSpan(0,0,0,5,0);
     ManagementScope scope = new ManagementScope("\\\\" + servername + "\\root\\cimv2", coptions);
     try
     {
      scope.Connect();
      ManagementPath mp = new ManagementPath("Win32_Service");
      mp.ClassName = "win32_Service=" + "\"" + servicename + "\"";
      ManagementClass mo = new ManagementClass (scope, mp, new  ObjectGetOptions(null, new TimeSpan(0,0,0,5), true) );
      ManagementBaseObject inParams = mo.GetMethodParameters (themethod);
      ManagementBaseObject mres = mo.InvokeMethod (themethod, inParams, options);
      string xx = mres["ReturnValue"].ToString(); // Win32 result of call
       
     }
     catch (Exception e)
     {
      Console.WriteLine("Failed to connect: " + e.Message);
     }
    }



  • MightnMagic

    Hi,

    You have been a life saver. It solved my problem. Can't thank you enough.



  • Stop a windows service on a remote machine