Remotely change computer name for a Windows Server 2008 machine using C#?

坚强是说给别人听的谎言 提交于 2019-12-04 17:11:39

Here is a nice link that discusses it in detail and also deals with active directory membership and machine naming in addition to the local machine name. http://derricksweng.blogspot.com/2009/04/programmatically-renaming-computer.html

(Btw, should you have to deal with Active Directory naming, I would consider using the ComputerPrincipal class from the System.DirectoryServices.AccountManagement namespace vice anything from System.DirectoryServices namespace that was used in the blog post.)

Tweaked code from the blog post (you will need to add a reference to System.Management to your project):

    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);

    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!