Recently I deployed some VMs on Azure. There was a small change to the naming convention afterwards so I wanted to rename the created VMs. This is how you can do this
#First login to your Azure Account
Login-AzureRmAccount
set-azurermcontext -subscriptionid "YourSubscription ID here"
# Set variables
$resourceGroup = "resourcegroup of VMs"
$oldvmName = "oldvmname"
$newvmName = "newvmname"
# Get the details of the VM to be renamed
$originalVM = Get-AzureRmVM `
-ResourceGroupName $resourceGroup `
-Name $oldvmName
# Remove the original VM
Remove-AzureRmVM -ResourceGroupName $resourceGroup -Name $oldvmName
# You receive an question if you would like to remove your VMs. You want do that. You can remove that question using the -force option
# Create the basic configuration for the replacement VM
$newVM = New-AzureRmVMConfig -VMName $newvmName -VMSize $originalVM.HardwareProfile.VmSize
set-AzureRmVMOSDisk -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-AzureRmVMDataDisk -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-AzureRmVMNetworkInterface `
-VM $newVM `
-Id $nic.Id
}
# Now recreate the VM using the new name but with the old disks, NIC etc
New-AzureRmVM `
-ResourceGroupName $resourceGroup `
-Location $originalVM.Location `
-VM $newVM `
-DisableBginfoExtension
After a couple of minutes (depending on the size of the VM) the newly created server with the old disks, NIC etc. is created. Currently this script doesn’t support renaming the NIC, disks to your naming convention. So they have the exact same name as before. When you assigned you NIC, disk etc a custom name you will see the old naming convention. Currently I’m working on it. 🙂