GooglePrettify

2019年7月12日 星期五

Start or Stop Services on Remote Machine

Sample code to control the remote machine/system services. Below code shows how to Start or Stop the remote computer service.

Note : To run this code user must have the rights to Start/Stop the service of the remote computer.

Namespace: 
       using System.Management;


Code: 

Start service of the Remote Machine:

              try
                {

                    #region Code to start the service
               
                    string serviceName = "Service1";
                    string IP="Remote machine IP";
                    string username ="UserID";
                    string password ="Pass";

                    ConnectionOptions connectoptions = new ConnectionOptions();
                    //connectoptions.Impersonation = ImpersonationLevel.Impersonate; 
                    connectoptions.Username = username;
                    connectoptions.Password = pass;

                    //IP Address of the remote machine
                  
                    ManagementScope scope = new ManagementScope(@"\\" + IP + @"\root\cimv2");
                    scope.Options = connectoptions;

                    //WMI query to be executed on the remote machine
                    SelectQuery query = new SelectQuery("select * from Win32_Service where name = '" + serviceName + "'");

                    using (ManagementObjectSearcher searcher = new
                                ManagementObjectSearcher(scope, query))
                    {
                        ManagementObjectCollection collection = searcher.Get();
                        foreach (ManagementObject service in collection)
                        {
                            if (service["Started"].Equals(false))
                            {
                                //Start the service
                                service.InvokeMethod("StartService", null);                              
                            }

                        }
                    }
                   
           #endregion

                }
                catch ()
                {
                  
                }


Similar way you can stop the service of Remote Machine:

                       if (service["Started"].Equals(true))
                        {
                            //Stop the service
                            service.InvokeMethod("StopService", null);                            
                        }

from : http://learn-vsdotnet.blogspot.com/2013/03/start-or-stop-services-on-remote-machine.html

沒有留言:

張貼留言