问题
Might someone be able to point me towards a conclusive resource to learn how to remotely change a computer name on a Windows Server 2008 machine using C#
I've looked at lots of sites for help and now in day two of my task and not really any closer (other than deciding WMI is pretty much my only option) Totally out of my normal skillset so I guess pretty much any info would be nice, but especially anything having to do with changing a computer name remotely. (this would occur right after I remotely spin up a virutal from an image...and yes, i realize a reboot will be required)
thanks
回答1:
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);
}
来源:https://stackoverflow.com/questions/6207411/remotely-change-computer-name-for-a-windows-server-2008-machine-using-c