PowerShell to rename a Hyper-V VM’s hostname from the Hyper-V host

PowerShell v3 in Windows Server 2012 opens up way more stuff than ever before for automation. I like my VMs to have a host name that matches the name I give the VM in on the Hyper-V host – that way when I write a PowerShell script to build 50 VMs they get useful names and they can all be created from the same VHD image. So I rename my Hyper-V VMs from my Hyper-V host.

I’ve shown lots of people this script at our UK IT Camps and generally people are all a bit like “why would you want to do that”. Well, personally, I create lots of demo enviornments but as a real IT guy you might want to quickly spin up a cloud.

Lets take a look at some PowerShell:

functionRename-UnknownVM ($VMtoRename,$NewVMName)
{


$vmip=Get-VMNetworkAdapter$VMToRename|whereswitchname-eq"CorpNet"| `


select-expandproperty"IPAddresses"|where {$_-match"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$"}


$vmHostName=[system.net.dns]::GetHostEntry($vmip)


$vmHostName=$vmHostName.HostName


Invoke-Command-ComputerName$vmHostName-ScriptBlock {


rename-Computer-NewName$args[0]-DomainCredentialcontoso\administrator-Restart } -ArgumentList$NewVMName
}
Rename-UnknownVM -VMtoRename rdsb -NewVMName rdsb 

So what’s happening, lets start at the bottom. Obviously everything is wrapped in a function to make it easy to call in the above RDSB  is the name of my VM – it’s the VM name and it’s the name that I want to rename it to. The function then goes and gets the named VM’s network adapter, it then finds just the network interface attached to a named virtual switched “CorpNet”, then we get the IP Address property which is stored as text so we match it on a RegEx. That gives us the IP of the VM.

Next we need to get the current name of the VM so we do that from DNS, we need this because the “rename-computer” cmdlet needs the name, not the IP Address a host to rename it.

Finally I use an invoke-commend script block to remotely execute the rename on the VM and the admin running the script is prompted for a password.

Simples. Actually not so much I’d like to thank Jonathan Noble for his help here.