編輯

共用方式為


使用 Azure PowerShell 變更 VM 的可用性設定組

適用於:✔️ Linux VM ✔️ Windows VM

下列步驟說明如何使用 Azure PowerShell 來變更虛擬機 (VM) 的可用性設定組。 您只能在建立 VM 時,將 VM 新增至可用性設定組。 若要變更可用性設定組,您必須刪除再重新建立 VM。

本文上次測試於 2019 年 2 月 12 日使用 Azure Cloud ShellAz PowerShell 模組 1.2.0 版。

警告

這隻是一個範例。 在某些情況下,您必須更新特定部署。

請確定磁碟的刪除選項設定為 detach。 如果它們設定為 delete,請先更新 VM,再刪除 VM。

如果您的 VM 已連結至負載平衡器,您必須更新腳本來處理該案例。

完成此程序之後,某些擴充功能可能也需要重新安裝。

如果您的 VM 使用混合式權益,您必須更新範例,以在新 VM 上啟用混合式權益。

必要條件

變更可用性設定組

下列腳本提供收集必要資訊的範例、刪除原始 VM,然後在新的可用性設定組中重新建立它:

  # Set variables
      $resourceGroup = "myResourceGroup"
      $vmName = "myVM"
      $newAvailSetName = "myAvailabilitySet"

  # Get the details of the VM to be moved to the availability set
      $originalVM = Get-AzVM `
        -ResourceGroupName $resourceGroup `
        -Name $vmName

  # Create a new availability set if it doesn't exist
      $availSet = Get-AzAvailabilitySet `
        -ResourceGroupName $resourceGroup `
        -Name $newAvailSetName `
        -ErrorAction Ignore
      if (-Not $availSet) {
      $availSet = New-AzAvailabilitySet `
        -Location $originalVM.Location `
        -Name $newAvailSetName `
        -ResourceGroupName $resourceGroup `
        -PlatformFaultDomainCount 2 `
        -PlatformUpdateDomainCount 2 `
        -Sku Aligned
      }

  # Remove the original VM
      Remove-AzVM -ResourceGroupName $resourceGroup -Name $vmName

  # Create the basic configuration for the replacement VM.
      $newVM = New-AzVMConfig `
        -VMName $originalVM.Name `
        -VMSize $originalVM.HardwareProfile.VmSize `
        -AvailabilitySetId $availSet.Id
  
  # For a Linux VM, change the last parameter from -Windows to -Linux
      Set-AzVMOSDisk `
        -VM $newVM -CreateOption Attach `
        -ManagedDiskId $originalVM.StorageProfile.OsDisk.ManagedDisk.Id `
        -Name $originalVM.StorageProfile.OsDisk.Name `
        -Windows

  # Add 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 NICs and keep the same NICs as primary; keep the private IP too, if it exists
      foreach ($nic in $originalVM.NetworkProfile.NetworkInterfaces) {	
      if ($nic.Primary -eq "True")
      {
              Add-AzVMNetworkInterface `
                -VM $newVM `
                -Id $nic.Id -Primary
                }
            else
                {
                  Add-AzVMNetworkInterface `
                  -VM $newVM `
                  -Id $nic.Id 
                  }
        }

  # Re-create the VM
      New-AzVM `
        -ResourceGroupName $resourceGroup `
        -Location $originalVM.Location `
        -VM $newVM `
        -DisableBginfoExtension