How To Rename an Azure Virtual Machine

8 Min. Read

Updated – 25/07/2024 – This article has been updated to consider renaming Azure Virtual Machine (VM) with multiple network interfaces (NICs).

Updated – 24/01/2023 – This article has been updated to consider renaming Azure Virtual Machine (VM) with Trusted Launch and Secure Boot enabled.

Updated – 07/03/2022 – Depending on how you delete a VM, it may only delete the VM resource, not the networking and disk resources. Microsoft has added a new capability where you can change the default settings for what other resources are deleted when you delete a VM (OS Disk, Data disk, and Network Interfaces). This article has been updated to take into consideration the recent changes by Microsoft and prevent disk deletion if you have this new option enabled.

In this article, we will share with you how to rename an Azure virtual machine using PowerShell. The same can apply whether you want to rename a Linux or Windows VM.

Introduction

Renaming an Azure VM is not a new problem. If you are coming from the on-premises world, you know how simple it is to rename a virtual machine in Hyper-V, VMware, or any other virtualization platform. This is not the case when you deploy a Virtual Machine using the Azure Portal, and you find yourself having to rename it afterward, you know how painful it is.

If you deploy your VMs with any infrastructure-as-code (IaC) tool such as ARM template, Bicep, or Terraform, or you use PowerShell or Azure CLI, then you can specify the Azure VM name at deployment time. But again, we can’t rename it after the deployment is completed.

Well, this is the purpose of this article, we have developed a nifty PowerShell tool that will help you to rename an Azure VM (Windows or Linux) by destroying the VM resource without touching the existing resources and then re-creating it with a new name and attach all the resources. This will apply to Azure virtual machine(s) with Managed Disks and Unmanaged Disks.

Related: If you want to rename the OS Disk for an Azure virtual machine, please check the following article.

Related: If you want to rename the Data Disks for an Azure virtual machine, please check the following article.

Related: If you want to rename the NIC interface for an Azure virtual machine, please check the following article.

Update the delete behavior on an existing VM

Updated – 07/03/2022 – Depending on how you delete a VM, it may only delete the VM resource, not the networking and disk resources. Microsoft has recently added a new capability where you can change the default settings for what other resources are deleted when you delete a VM (OS Disk, Data Disk, and Network Interface) delete option.

By default, disks, NICs, and Public IPs associated with a VM are persisted when the VM is deleted. However, if you configured these resources to be automatically deleted, then make sure to update the settings before you run the PowerShell (Rename-AzVM.ps1) tool below so the resources remain after the VM is deleted. The PowerShell tool was also updated to take into consideration this new behavior and prevent renaming the VM if the delete behavior is set to “Delete“.

To keep these resources intact, we need to use and set the (deleteOption) property to “Detach” by using the Azure REST API to change the behavior when you delete a VM. At the time of this writing, updating the behavior when you delete a VM is not supported with the Azure portal, Azure CLI, or Azure PowerShell.

The following REST API example will update the VM delete behavior to “Detach” instead of “Delete” so the NIC, OS disk, and data disk will be preserved when the VM is deleted.

I strongly recommend running the Get (REST API) first before performing the Update: Run Virtual Machines – Get REST API to verify the current delete behavior of your existing VM.

Then make sure to update the {subscriptionId}, {RGName}, and {vmName} values before you update the virtual machine. You can perform this operation directly using the Microsoft REST API service here.

PATCH https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{RGName}/
providers/Microsoft.Compute/virtualMachines/{vmName}?api-version=2021-07-01 

{ 
    "properties": {        
        "hardwareProfile": { 
            "vmSize": "Standard_D2s_v3" 
        }, 
        "storageProfile": { 
            "imageReference": { 
                "publisher": "MicrosoftWindowsServer", 
                "offer": "WindowsServer", 
                "sku": "2019-Datacenter", 
                "version": "latest", 
                "exactVersion": "17763.3124.2111130129" 
            }, 
            "osDisk": { 
                "osType": "Windows", 
                "name": "OsDisk_1", 
                "createOption": "FromImage", 
                "caching": "ReadWrite", 
                "managedDisk": { 
                    "storageAccountType": "Premium_LRS", 
                    "id": "/subscriptions/subID/resourceGroups/resourcegroup/providers/Microsoft.Compute/disks/OsDisk_1" 
                }, 
                "deleteOption": "Detach", 
                "diskSizeGB": 127 
            }, 
            "dataDisks": [ 
                { 
                    "lun": 0, 
                    "name": "DataDisk_0", 
                    "createOption": "Attach", 
                    "caching": "None", 
                    "writeAcceleratorEnabled": false, 
                    "managedDisk": { 
                        "storageAccountType": "Premium_LRS", 
                        "id": "/subscriptions/subID/resourceGroups/resourcegroup/providers/Microsoft.Compute/disks/DataDisk_0" 
                    }, 
                    "deleteOption": "Detach", 
                    "diskSizeGB": 1024, 
                    "toBeDetached": false 
                }, 
                { 
                    "lun": 1, 
                    "name": "DataDisk_1", 
                    "createOption": "Attach", 
                    "caching": "None", 
                    "writeAcceleratorEnabled": false, 
                    "managedDisk": { 
                        "storageAccountType": "Premium_LRS", 
                        "id": "/subscriptions/subID/resourceGroups/resourcegroup/providers/Microsoft.Compute/disks/DataDisk_1" 
                    }, 
                    "deleteOption": "Detach", 
                    "diskSizeGB": 1024, 
                    "toBeDetached": false 
                } 
            ] 
        }, 
        "osProfile": { 
            "computerName": "testvm", 
            "adminUsername": "azureuser", 
            "windowsConfiguration": { 
                "provisionVMAgent": true, 
                "enableAutomaticUpdates": true, 
                "patchSettings": { 
                    "patchMode": "AutomaticByOS", 
                    "assessmentMode": "ImageDefault", 
                    "enableHotpatching": false 
                } 
            }, 
            "secrets": [], 
            "allowExtensionOperations": true, 
            "requireGuestProvisionSignal": true 
        }, 
        "networkProfile": { 
            "networkInterfaces": [ 
                { 
                    "id": "/subscriptions/subID/resourceGroups/resourcegroup/providers/Microsoft.Network/networkInterfaces/nic336" 
                , 
                   "properties": { 
                   "deleteOption": "Detach" 
} 
} 
            ] 
        } 
} 
}

Rename Azure VM

You have a couple of options to run the script, you can either use the Azure Cloud Shell, Visual Studio (VS) Code, or the new Windows Terminal. The Script works with PowerShell 5.1 or PowerShell 7.3.x (core) with the Az module installed.

You can use the following PowerShell command to install and update the “Az module” locally on your machine.

# Make sure you have the latest version of PowerShellGet installed
Install-Module -Name PowerShellGet -Force

 # Install and update to the latest Az PowerShell module
Install-Module -Name Az -AllowClobber -Force

.EXAMPLE

.\Rename-AzVM.ps1 -resourceGroup [ResourceGroupName] -OldVMName [VMName] -NewVMName [VMName] -Verbose

This example will rename an existing Azure virtual machine, you need to specify the Resource Group name, the old VM name, and the new VM name. The script will preserve the old VM settings and resources, and then apply them to the new Azure VM whether it’s Windows or Linux.

Please note that the tool below was updated to work for virtual machines with Azure Managed Disks and UnManaged Disks. If you still have very old VMs with UnManaged Disks, we highly recommend converting them to unmanaged disks as described in this article.

Here is an example of the output once you run this tool:

Rename Azure Virtual Machine

PowerShell Code

The complete script is detailed below to automate the entire VM rename process:

<#
.SYNOPSIS
Rename Azure VM.

.DESCRIPTION
Rename an Azure virtual machine for Linux and Windows OS.

.NOTES
File Name : Rename-AzVM.ps1
Author    : Microsoft MVP/MCT - Charbel Nemnom
Version   : 2.4
Date      : 29-August-2021
Update    : 25-July-2024
Requires  : PowerShell 5.1 or PowerShell 7.2.x (Core)
Module    : Az Module
OS        : Windows or Linux VMs
Support   : Managed and UnManaged Disks   

.LINK
To provide feedback or for further assistance please visit: https://charbelnemnom.com

.EXAMPLE
.\Rename-AzVM.ps1 -resourceGroup [ResourceGroupName] -OldVMName [VMName] -NewVMName [VMName] -Verbose
This example will rename an existing Azure virtual machine, you need to specify the Resource Group name, old VM name and the new VM name.
The script will preserve the old VM settings and resources, and then apply them to the new Azure VM.
#>

[CmdletBinding()]
Param (
    [Parameter(Position = 0, Mandatory = $true, HelpMessage = 'Enter the Resource Group of the Azure VM')]
    [Alias('rg')]
    [String]$resourceGroup,

    [Parameter(Position = 1, Mandatory = $True, HelpMessage = 'Enter the existing Azure VM name')]
    [Alias('OldVM')]
    [String]$OldVMName,

    [Parameter(Position = 2, Mandatory = $true, HelpMessage = 'Enter the desired new Azure VM name')]
    [Alias('NewVM')]
    [String]$NewVMName
)

#! Check Azure Connection
Try {
    Write-Verbose "Connecting to Azure Cloud..."
    Connect-AzAccount -ErrorAction Stop | Out-Null
}
Catch {
    Write-Warning "Cannot connect to Azure Cloud. Please check your credentials. Exiting!"
    Break
}

$azSubs = Get-AzSubscription
$azSub = 0
Do {
    Write-Verbose "Set Azure Subscription context to: $($azSubs[$azSub].Name)"
    Set-AzContext -Subscription $azSubs[$azSub] | Out-Null
    $VMInfo = Get-AzVM | Where-Object { $_.Name -eq $OldVMName -and $_.ResourceGroupName -eq $resourceGroup }
    if ($VMInfo) {
        #! Get original Azure VM properties and export it
        Try {
            Write-Verbose "Get original Azure VM properties and export its configuration to $(get-location)"
            Get-AzVM -ResourceGroupName $resourceGroup -Name $OldVMName -ErrorAction Stop | Export-Clixml .\AzVM_Backup.xml -Depth 5
        }
        Catch {
            Write-Warning "Cannot Export Azure VM $OldVMName to $(get-location) - Exiting!"
            Break
        }
    }
    $azSub++
} while ((!$VMInfo) -and ($azSub -lt $azSubs.count))

If (!$VMInfo) {
    Write-Warning "The Azure VM $OldVMName does not exist. Please check your virtual machine name!"
    Exit
}

#! Import Azure VM settings from backup XML and store it in a variable
Write-Verbose "Importing the old Azure VM properties..."
$oldVM = Import-Clixml .\AzVM_Backup.xml

#! Check if the delete behavior on existing VM is set to "Delete"
If ($oldVM.StorageProfile.OsDisk.DeleteOption -eq "Delete") {
    Write-Warning "The Azure VM $($OldVMName) has the OS Disk Deletion set to [Delete]. Please update it to [Detach] before you continue renaming your virtual machine. Exiting!"
    Exit
}

If ($oldVM.StorageProfile.DataDisks.DeleteOption -contains "Delete") {
    Write-Warning "The Azure VM $($OldVMName) has the Data Disk Deletion set to [Delete]. Please update it to [Detach] before you continue renaming your virtual machine. Exiting!"
    Exit
}

If ($oldVM.NetworkProfile.NetworkInterfaces.DeleteOption -eq "Delete") {
    Write-Warning "The Azure VM $($OldVMName) has the NIC Interface Deletion set to [Delete]. Please update it to [Detach] before you continue renaming your virtual machine. Exiting!"
    Exit 
}

#! Delete the Old Azure VM
Write-Verbose "Deleting the old Azure VM and keeping the other resources intact..."
Remove-AzVM -ResourceGroupName $oldVM.ResourceGroupName -Name $oldVM.Name -Force

#! Creating the new Azure VM configuration
Write-Verbose "Creating the new Azure VM configuration..."
$newVM = New-AzVMConfig -VMName $NewVMName -VMSize $oldVM.HardwareProfile.VmSize -Tags $oldVM.Tags

#! Attaching the OS Managed Disk of the old VM to the new Azure VM (Windows/Linux)
if ($oldVM.StorageProfile.OsDisk.vhd -eq $null -and $oldvm.StorageProfile.osdisk.ostype.value -eq "Windows") {
    Write-Verbose "Attaching the Windows OS Managed Disk of the old VM to the new Azure VM..."
    Set-AzVMOSDisk -VM $newVM -CreateOption Attach -ManagedDiskId $oldVM.StorageProfile.OsDisk.ManagedDisk.Id -Name $oldVM.StorageProfile.OsDisk.Name -Windows -Caching $oldVM.StorageProfile.OsDisk.Caching.Value | Out-Null
}
elseif ($oldVM.StorageProfile.OsDisk.vhd -eq $null -and $oldvm.StorageProfile.osdisk.ostype.value -eq "Linux") {
    Write-Verbose "Attaching the Linux OS Managed Disk of the old VM to the new Azure VM..."
    Set-AzVMOSDisk -VM $newVM -CreateOption Attach -ManagedDiskId $oldVM.StorageProfile.OsDisk.ManagedDisk.Id -Name $oldVM.StorageProfile.OsDisk.Name -Linux -Caching $oldVM.StorageProfile.OsDisk.Caching.Value | Out-Null
}

#! Attaching the OS UnManaged Disk of the old VM to the new Azure VM (Windows/Linux)
if ($oldVM.StorageProfile.OsDisk.vhd -ne $null -and $oldvm.StorageProfile.osdisk.ostype.value -eq "Windows") {
    Write-Verbose "Attaching the Windows OS UnManaged Disk of the old VM to the new Azure VM..."
    Set-AzVMOSDisk -VM $newVM -CreateOption Attach -VhdUri $oldVM.StorageProfile.OsDisk.vhd.value -Name $oldVM.StorageProfile.OsDisk.Name -Windows -Caching $oldVM.StorageProfile.OsDisk.Caching.Value | Out-Null
}
elseif ($oldVM.StorageProfile.OsDisk.vhd -ne $null -and $oldvm.StorageProfile.osdisk.ostype.value -eq "Linux") {
    Write-Verbose "Attaching the Linux OS UnManaged Disk of the old VM to the new Azure VM..."
    Set-AzVMOSDisk -VM $newVM -CreateOption Attach -VhdUri $oldVM.StorageProfile.OsDisk.vhd.value -Name $oldVM.StorageProfile.OsDisk.Name -Linux -Caching $oldVM.StorageProfile.OsDisk.Caching.Value | Out-Null
}

# Checking if the old VM is deployed with Trusted Launch enabled
$securityType = Get-AzDisk -Name $oldVM.StorageProfile.OsDisk.Name
Write-Verbose "Checking if the old VM is deployed with Trusted Launch enabled..."
if ($securityType.SecurityProfile.SecurityType -eq "TrustedLaunch") {
    Write-Verbose "Setting the OS Disk Security Profile to [TrustedLaunch] and enable [SecureBoot]"
    $newVM = Set-AzVmSecurityProfile -VM $newVM -SecurityType "TrustedLaunch" 
    $newVM = Set-AzVmUefi -VM $newVM -EnableVtpm $true  -EnableSecureBoot $true 
}

#! Attaching all NICs of the old VM to the new Azure VM
Write-Verbose "Attaching all NICs of the old VM to the new Azure VM..."
$oldVM.NetworkProfile.NetworkInterfaces.Item(0).primary = $true
$oldVM.NetworkProfile.NetworkInterfaces | % { Add-AzVMNetworkInterface -VM $newVM -Id $_.Id } | Out-Null

#! Attaching all Data Disks (if any) of the old VM to the new Azure VM
Write-Verbose "Attaching all Data Disks (if any) of the old VM to the new Azure VM..."
$oldVM.StorageProfile.DataDisks | % { Add-AzVMDataDisk -VM $newVM -Name $_.Name -ManagedDiskId $_.ManagedDisk.Id -Caching $_.Caching -Lun $_.Lun -DiskSizeInGB $_.DiskSizeGB -CreateOption Attach }

#! Creating the new Azure VM
Write-Verbose "Creating the new Azure VM..."
New-AzVM -ResourceGroupName $oldVM.ResourceGroupName -Location $oldVM.Location -VM $newVM

If you look back in the Azure Portal, we can see that the old VM name is renamed successfully.

Rename Azure VM - Resource Group
Confirm by looking for the VM in the Azure Portal under the resource group

If you have any feedback or changes that everyone should receive, please feel free to leave a comment below.

That’s it there you have it. Happy Azure VM Renaming!

Summary

In this article, you have learned how to rename an Azure virtual machine using PowerShell. We first back up the VM configuration and export it to an (.XML) file for later reference, then delete a VM, package a new VM configuration, attach all disks and network profiles, and finally create the new VM.

Please note that the PowerShell script outlined above is for a basic VM. There might be other important details that need to be included in the renamed virtual machine. Because some settings can only be set during the creation so these must be carefully considered too before running the script.

A couple of examples where careful planning is required, Availability Set to which the VM can be added only when the VM is created, however, you can change the Availability Set for an Azure VM using Azure PowerShell as described here, another example is if the VM is attached to a load balancer, attached to an Azure Application Gateway, or protected with Azure Backup.

We highly recommend planning carefully before you proceed with the renaming process to increase the chance of success.

__
Thank you for reading my blog.

If you have any questions or feedback, please leave a comment.

-Charbel Nemnom-

Previous

Migrating Your Video Pipeline to Azure Media Services

Enable Azure SQL Auditing with Azure Policy

Next

27 thoughts on “How To Rename an Azure Virtual Machine”

Leave a comment...

  1. Another issue is that not all VMs in Azure use ManagedDisks. The command below fails

    Set-AzVMOSDisk -VM $newVM -CreateOption Attach -ManagedDiskId $oldVM.StorageProfile.OsDisk.ManagedDisk.Id -Name $oldVM.StorageProfile.OsDisk.Name -Windows | Out-Null

    I had to manually modify the script to this:

    Set-AzVMOSDisk -VM $newVM -Name $oldVM.StorageProfile.OsDisk.Name -Caching ReadWrite -Windows -CreateOption “Attach” -VhdUri ‘https://randompath.blob.core.windows.net/vhds/osdiskname.vhd’

  2. Hello G.B, thanks for the feedback!
    Please note that the tool was developed to work only with Managed Disks since most of the deployment is set by default to Managed Disks.
    I have updated the logic to take into consideration the two types of Managed and Unmanaged Disks.
    For folks who still using Unmanaged Disks, the tool should work now for both.
    Thanks!

  3. WARNING: Since the VM is created using premium storage or managed disk, existing standard storage account, stggidiag, is used for boot diagnostics.
    New-AzVM: /home/utornqvi/Rename-AzVM.ps1:108
    Line |
    108 | New-AzVM -ResourceGroupName $oldVM.ResourceGroupName -Location $oldVM …
    | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    | Disk tic-dr-qa_disk1_0508288658b4432baf815ff2ff994159 is not found. ErrorCode: NotFound ErrorMessage: Disk tic-dr-qa_disk1_0508288658b4432baf815ff2ff994159 is not found.

  4. Hello Ulf, thanks for the comment!
    I have updated the PowerShell script, could you please retry and see if it resolve your issue?
    Best regards to Volvo, my favorite car!

  5. “message”: “Missing closing ‘)’ after expression in ‘If’ statement.”,
    “startLineNumber”: 93,
    “startColumn”: 71,

  6. Thank you Adrian for the good catch,
    I have added the missing ‘)’ after the ‘If’ statement.
    The tool is updated!

  7. Hi Charbel… If the VM is protected with Azure Backup, will the script successfully transfer the backup schedule to the new one?

    Do we have to stop the backup instance of the old VM first?

  8. Hello Santo, thanks for the comment and the excellent question!
    No, the script will NOT transfer the backup schedule nor reprotect the new VM.
    After the fact, you need to re-enable Azure Backup protection for the new VM Name.
    Please note that the existing backup for the old VM won’t be touched in the Recovery Services Vault, so you can still restore and recover if needed.
    I will add this note to the next update of this tool and automate this capability as well.
    Hope it helps!

  9. Thanks for sharing the script, it works perfectly but every time this script creates a new storage account, I tested it a couple of times first time it creates a new standard storage account for boot diagnostics, but it creates a new storage account every time you run the script.
    Can we delete this storage account once the task is completed?

  10. Hello Indu, thank you for the feedback!
    I am happy to hear that it’s working for you.
    Are you renaming Azure VM with Managed Disks or Unmanaged Disks?
    Yes, you can delete the storage account (if not being used) once the task is completed.
    Please note that the script does NOT create a new standard storage account for boot diagnostics.
    However, if the Azure VM you are renaming has boot diagnostics enabled, then the script will preserve the storage account and use it for boot diagnostics after the fact.
    Hope it helps!

  11. Hi,
    I run the script on VM with two nic interfaces, and faced the following error:

    New-AzVM : Virtual machine AZR-VM02 must have one network interface set as the primary.
    ErrorCode: VirtualMachineMustHaveOneNetworkInterfaceAsPrimary
    ErrorMessage: Virtual machine AZR-VM02 must have one network interface set as the primary.
    ErrorTarget:
    StatusCode: 400
    ReasonPhrase:
    OperationID : bf290802-8742-405b-8300-878e43a98f4a
    Au caractère D:\AZURESCRIPT\Rename-AzVM.ps1:145 : 1
    + New-AzVM -ResourceGroupName $oldVM.ResourceGroupName -Location $oldVM …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : CloseError : (:) [New-AzVM], ComputeCloudException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.NewAzureVMCommand

  12. Hello Soufiane, thanks for testing the script and sharing your experience!
    Since you have a VM with two NIC interfaces, we need to set one network interface as the primary, as the error shows.
    I have updated the script to handle this scenario as well.
    Please get a new copy of the script above version 2.4 and let me know if it works for you.
    Hope it helps!

  13. Hello,
    I’ve been running the latest script for a few weeks now but now it gets an error that it can’t find the old VM. It successfully authenticates in the browser session and displays the subscription list and default. I’m positive the rg, old, and new vm names are being entered correctly.

    Thanks,
    Dan

  14. Hi Dan, thanks for the comment and the update!
    This error usually occurs when the script context doesn’t match the VM scope. Please double-check that the correct subscription is selected and that the VM still exists in the specified resource group (and wasn’t renamed or moved previously). Also, make sure there’s no trailing space or case mismatch in the VM name.
    Since the script was working for a few weeks, something may have changed in the environment. If the issue persists, please share the exact error message/output so I can help pinpoint it quickly.

  15. Hello Charbel,
    Thanks for the quick response back.
    It was later discovered that I was entering an _ instead of the – in the VM name. It worked fine after changing that.
    Is there a signed copy of the signed copy of the script available to download?

    Dan

Let us know what you think, or ask a question...