使用 PowerShell 更改 Azure VM 使用的 OS 磁盘Change the OS disk used by an Azure VM using PowerShell

如果当前具备 VM,但希望将磁盘更换为备份磁盘或其他 OS 磁盘,可使用 Azure PowerShell 更换 OS 磁盘。If you have an existing VM, but you want to swap the disk for a backup disk or another OS disk, you can use Azure PowerShell to swap the OS disks. 无需删除和重新创建 VM。You don't have to delete and recreate the VM. 甚至可在另一资源组中使用托管磁盘,只要该磁盘尚未使用。You can even use a managed disk in another resource group, as long as it isn't already in use.

需要停止/取消分配 VM,然后才可将该托管磁盘的资源 ID 替换为其他托管磁盘的资源 ID。The VM does need to be stopped\deallocated, then the resource ID of the managed disk can be replaced with the resource ID of a different managed disk.

请确保 VM 大小和存储类型与要附加的磁盘兼容。Make sure that the VM size and storage type are compatible with the disk you want to attach. 例如,如果要使用的磁盘位于高级存储中,则 VM 需要能使用高级存储(如 DS 系列大小)。For example, if the disk you want to use is in Premium Storage, then the VM needs to be capable of Premium Storage (like a DS-series size). 这两个磁盘的大小也必须相同。Both disks must also be the same size. 此外,不支持将未加密的 VM 与加密的 OS 磁盘混合使用。And ensure that you're not mixing an un-encrypted VM with an encrypted OS disk, this is not supported. 如果 VM 不使用 Azure 磁盘加密,则要交换的 OS 磁盘不应使用 Azure 磁盘加密。If the VM doesn't use Azure Disk Encryption, then the OS disk being swapped in shouldn't be using Azure Disk Encryption.

使用 Get-AzDisk 获取资源组中的磁盘列表Get a list of disks in a resource group using Get-AzDisk

Get-AzDisk -ResourceGroupName myResourceGroup | Format-Table -Property Name

如果知道要使用的磁盘的名称,请将其设置为该 VM 的 OS 磁盘。When you have the name of the disk that you would like to use, set that as the OS disk for the VM. 此示例停止/取消分配名为 myVM 的 VM,并将名为 newDisk 的磁盘分配为新的 OS 磁盘 。This example stop\deallocates the VM named myVM and assigns the disk named newDisk as the new OS disk.

# Get the VM 
$vm = Get-AzVM -ResourceGroupName myResourceGroup -Name myVM 

# Make sure the VM is stopped\deallocated
Stop-AzVM -ResourceGroupName myResourceGroup -Name $vm.Name -Force

# Get the new disk that you want to swap in
$disk = Get-AzDisk -ResourceGroupName myResourceGroup -Name newDisk

# Set the VM configuration to point to the new disk  
Set-AzVMOSDisk -VM $vm -ManagedDiskId $disk.Id -Name $disk.Name 

# Update the VM with the new OS disk
Update-AzVM -ResourceGroupName myResourceGroup -VM $vm 

# Start the VM
Start-AzVM -Name $vm.Name -ResourceGroupName myResourceGroup

后续步骤Next steps

要创建磁盘副本,请参阅拍摄磁盘快照To create a copy of a disk, see Snapshot a disk.