Renaming a VM

When creating a VM in Azure, you need to be certain of the name you provide it at the beginning; there is no way to rename it after, which can be a hassle if you need to change it for whatever reason.

The only way to rename a VM resource in Azure is to delete it and rebuild it. By deleting it, you are actually deleting the VM resource itself, or shell if you will; the other resources that make the VM remain intact, including the NIC and disk. 

Deleting VM’s in Azure leaves the associated NIC’s and disk’s as remnants until you actually delete these too. It is best to ensure you have delete these too, especially managed disks as you will still be billed by Azure to host them, even if they are not assigned to a VM. 

Important: If the VM has Azure Disk Encryption (ADE) enabled, it is best to use Azure Backup and restore copy with the desired name from backup. If you not use Azure Backup, you will need to disable BitLocker encryption and disable the associated extension before renaming the VM.

The script below will rename an existing VM by deleting it and reassembling the resources with a new VM of the desired name:

#First login to your Azure Account

Connect-AzAccount
Set-AzContext -subscriptionid "SubscriptionID"
# Set variables
$resourceGroup = "RGName"
$oldvmName = "OldlVMName"
$newvmName = "NewVMName"
# Get the details of the VM to be renamed
$originalVM = Get-AzVM -ResourceGroupName $resourceGroup -Name $oldvmName
# Remove the original VM
Remove-AzVM -ResourceGroupName $resourceGroup -Name $oldvmName   
# You receive an question if you would like to remove your VMs. You want to do that. You can remove that question using the -force option
# Create the basic configuration for the replacement VM
$newVM = New-AzVMConfig -VMName $newvmName -VMSize $originalVM.HardwareProfile.VmSize
Set-AzVMOSDisk -VM $newVM -CreateOption Attach -ManagedDiskId $originalVM.StorageProfile.OsDisk.ManagedDisk.Id -Name $originalVM.StorageProfile.OsDisk.Name -Windows
# Now let's add the data disks
foreach ($disk in $originalVM.StorageProfile.DataDisks) 
Add-AzVMDataDisk -VM $newVM -Name $disk.Name -ManagedDiskId $disk.ManagedDisk.Id -Caching $disk.Caching -Lun $disk.Lun -DiskSizeInGB $disk.DiskSizeGB -CreateOption Attach
}
# Add the original NIC(s)
foreach ($nic in $originalVM.NetworkProfile.NetworkInterfaces) 
{
Add-AzVMNetworkInterface -VM $newVM -Id $nic.Id
}
# Now recreate the VM using the new name but with the old disks, NIC etc
New-AzVM -ResourceGroupName $resourceGroup -Location $originalVM.Location -VM $newVM -DisableBginfoExtension