开发者

Modify the code to perform operation on remote servers

开发者 https://www.devze.com 2023-01-22 02:44 出处:网络
I wrote the following code to change the user account and password associated with a Windows Service. How can I modify this code to be able to perform the same operation on a remote system?

I wrote the following code to change the user account and password associated with a Windows Service. How can I modify this code to be able to perform the same operation on a remote system?

static void Main(string[] args)
        {
            string serviceName = "DummyService";
            string username = ".\\Service_Test2";
            string password = "Password1";

            ServiceController sc = new ServiceController(serviceName);

            Console.WriteLine(sc.Status.ToString());

            if (sc.Status == ServiceControllerStatus.Running)
            {
                sc.Stop();
        开发者_开发技巧    }
            Thread.Sleep(2000);
            sc.Refresh();
            Console.WriteLine(sc.Status.ToString());

            string objPath = string.Format("Win32_Service.Name='{0}'", serviceName);
            using (ManagementObject service = new ManagementObject(new ManagementPath(objPath)))
            {
                object[] wmiParams = new object[11];
                wmiParams[6] = username;
                wmiParams[7] = password;
                service.InvokeMethod("Change", wmiParams);
            }

            Thread.Sleep(2000);

            Console.WriteLine(sc.Status.ToString());

            if (sc.Status == ServiceControllerStatus.Stopped)
            {
                sc.Start();
            }
            Thread.Sleep(2000);
            sc.Refresh();
            Console.WriteLine(sc.Status.ToString());

        }


  1. Use ServiceController constructor overload that allows target machine-name to be specified

  2. Modify WMI object path to include the target server.

        new ManagementPath(
        "\\\\ComputerName\\root" +
        "\\cimv2:Win32_Service.Name='{0}'");
    
  3. Make sure your user/password have sufficient rights on target machine, change those if not.

0

精彩评论

暂无评论...
验证码 换一张
取 消