Change size for Virtual Machines in availability set with Powershell

To change VM Size when your virtual machines are part of an availability set can be a pain in the Azure Portal. Especially if the new size you want is not available on your current cluster and the resources have to be moved as well.

The entire process is a lot easier to do with powershell

 1Login-AzureRmAccount
 2 
 3$rg_name = "RG-ResizeDemo"
 4$as_name = "AS-ResizeDemo"
 5$new_vm_size = "Standard_B2s"
 6$as = Get-AzureRmAvailabilitySet -ResourceGroupName $rg_name
 7$vm_ids = $as.VirtualMachinesReferences
 8 
 9foreach ($vm_id in $vm_ids) {
10    $s = $vm_id.Id.Split("/")
11    $vm_name = $s[8]
12    Stop-AzureRmVM -ResourceGroupName $rg -Name $vm_name -Force
13}
14 
15foreach ($vm_id in $vm_ids) {
16    $s = $vm_id.Id.Split("/")
17    $vm_name = $s[8]
18    $vm = Get-AzureRmVM -ResourceGroupName $rg -name $vm_name
19    $vm.HardwareProfile.VmSize = $new_vm_size
20    Update-AzureRmVM -ResourceGroupName $rg -VM $vm
21    Start-AzureRmVM -ResourceGroupName $rg -Name $vm_name
22}