修改代码以在远程服务器上执行操作

时间:2010-10-25 16:55:18

标签: c# service

我编写了以下代码来更改与Windows服务关联的用户帐户和密码。如何修改此代码以便能够在远程系统上执行相同的操作?

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 个答案:

答案 0 :(得分:2)

  1. 使用允许指定目标计算机名称的ServiceController constructor overload

  2. 修改WMI对象路径以包含目标服务器。

        new ManagementPath(
        "\\\\ComputerName\\root" +
        "\\cimv2:Win32_Service.Name='{0}'");
    
  3. 确保您的用户/密码在目标计算机上拥有足够的权限,如果没有则更改。