When you are managing a large number of virtual machines, it can get tricky to keep track of everything. One thing that I see many people doing to help with this is to make sure that the guest operating system has the same network name as the virtual machine name. This makes life a lot easier when moving between different tools.
However, I tend to rename and copy virtual machines a lot, which makes it difficult to keep the virtual machine and guest operating system name synchronized. To handle this I wrote the following script:
# Get the virtual machine name from the parent partition
$vmName = (Get-ItemProperty –path “HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters”).VirtualMachineName
# Replace any non-alphanumeric characters with an underscore
$vmName = [Regex]::Replace($vmName,"\W","_")
# Trim names that are longer than 15 characters
$vmName = $vmName.Substring(0,[System.Math]::Min(15, $vmName.Length))
# Check the trimmed and cleaned VM name against the guest OS name
# If it is different, change the guest OS name and reboot
if ($env:computername -ne $vmName) {(gwmi win32_computersystem).Rename($vmName); shutdown -r -t 0}
What this script does is:
- Read the virtual machine name from the registry inside the virtual machine
- Clean up the virtual machine name and check it against the guest OS name
- If they match, move along
- If they do not match, rename the guest operating system and reboot
I have this script inside my virtual machines, configured to run automatically when the guest operating system boots.
Cheers,
Ben