使用C#远程更改Windows Server 2008计算机的计算机名称?

J B*_*min 2 c# wmi remote-access windows-server-2008-r2

也许有人能指出我朝着一个决定性的资源来学习如何使用C#在Windows Server 2008的计算机上远程更改计算机名

我已经看了很多网站寻求帮助,现在我的任务的第二天并没有真正的任何接近(除了决定WMI几乎是我唯一的选择)完全超出我的正常技能组所以我猜几乎任何信息都是很好,但尤其是与远程更改计算机名称有关的任何事情.(这会在我从图像远程旋转虚拟现象后发生......是的,我意识到需要重新启动)

谢谢

Jas*_*son 5

这是一个很好的链接,详细讨论它,除了本地机器名称外,还处理活动目录成员身份和机器命名. http://derricksweng.blogspot.com/2009/04/programmatically-renaming-computer.html

(顺便说一句,如果你必须处理Active Directory命名,我会考虑使用System.DirectoryServices.AccountManagement命名空间中的ComputerPrincipal类,以及博客文章中使用的System.DirectoryServices命名空间中的任何内容.)

来自博客文章的调整代码(您需要在项目中添加对System.Management的引用):

    public void RenameRemotePC(String oldName, String newName, String domain, NetworkCredential accountWithPermissions)
    {
        var remoteControlObject = new ManagementPath
                                      {
                                          ClassName = "Win32_ComputerSystem",
                                          Server = oldName,
                                          Path =
                                              oldName + "\\root\\cimv2:Win32_ComputerSystem.Name='" + oldName + "'",
                                          NamespacePath = "\\\\" + oldName + "\\root\\cimv2"
                                      };

        var conn = new ConnectionOptions
                                     {
                                         Authentication = AuthenticationLevel.PacketPrivacy,
                                         Username = oldName + "\\" + accountWithPermissions.UserName,
                                         Password = accountWithPermissions.Password
                                     };

        var remoteScope = new ManagementScope(remoteControlObject, conn);

        var remoteSystem = new ManagementObject(remoteScope, remoteControlObject, null);

        ManagementBaseObject newRemoteSystemName = remoteSystem.GetMethodParameters("Rename");
        var methodOptions = new InvokeMethodOptions();

        newRemoteSystemName.SetPropertyValue("Name", newName);
        newRemoteSystemName.SetPropertyValue("UserName", accountWithPermissions.UserName);
        newRemoteSystemName.SetPropertyValue("Password", accountWithPermissions.Password);

        methodOptions.Timeout = new TimeSpan(0, 10, 0);
        ManagementBaseObject outParams = remoteSystem.InvokeMethod("Rename", newRemoteSystemName, null);

    }
Run Code Online (Sandbox Code Playgroud)