Thursday, December 2, 2021

Resize Azure VMs using Az powershell.

Script to resize Azure VM's from any subscription. If a VM is stopped it will resize it. If it is running it will stop the VM and resize it.


#$NewSize = "Standard_D8s_v3"

$NewSize = "Standard_E4s_v3" 

#$NewSize = "Standard_DS1_v2"

Function Out($message) {
$message = $(Get-Date -Format "MM/dd/yyyyTHH:mm:ss") + ":" + $message
Write-Output $message}

Out "Vm resize script starting...."

function Connect($tenantid)
{
$username = "username@contoso.com"
$password = ConvertTo-SecureString -AsPlainText -Force "password" 
$pscredential = New-Object -TypeName System.Management.Automation.PSCredential($username$password)
Connect-AzAccount -Credential $pscredential -Tenant $tenantId -EnvironmentName AzureUSGovernment
}

Function Resize-VM($VM)
{
 
  Out "Resizing $($vm.name) in $($vm.ResourceGroupName) from $($VM.HardwareProfile.VmSize) to $NewSize"          ## Change here
   $VM.HardwareProfile.VmSize = $NewSize
  Update-AzVM -ResourceGroupName $vm.ResourceGroupName -VM $VM 
}


Function CheckVM($VM)
{            
   if((Get-AzVM -Name $VM.Name -Status).PowerState -eq "VM running")
     {
       Out "$($VM.Name) is resized and Started"
     }
     else {
         Out "$($VM.Name) is resized and not started"
      }
     
}

Connect "put your tenant id here"


$VMList = @("VM1","VM2" ## comma separated list of VM's
)
$Allsubs = Get-AzSubscription 

foreach($sub in $Allsubs)

{
   Select-AzSubscription -SubscriptionId $sub.SubscriptionId | Out-Null
  $VMS = Get-AzVM -Status 
 
foreach($vm in $VMS)
{
 
 foreach($v in $VMList)
   {
     if($v -eq $Vm.name)
      {
        
      if($vm.PowerState -notmatch "VM running"## If the VM is switched off.We resize but dont start it.
        {
          #Resize the vm
          Out "VM $($VM.Name) is already powered off.Resizing...."
          Resize-VM $VM
          
        }

     Else # If the VM is turned on. Turn it off, resize and start it.
        {
          Out "VM is powered on. So Stopping $($VM.Name)"
          Stop-AzVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Force
          Start-Sleep -Seconds 120
          #Get VM Status
          if((Get-AzVM -Name $VM.Name -Status).PowerState -eq "VM deallocated")
             {
               Out "$($VM.Name) is now off. Resizing...."
               Resize-VM $VM
               Start-AzVM -Name $VM.Name -ResourceGroupName $VM.ResourceGroupName
               Start-Sleep -Seconds 300
               CheckVM $VM

         }
                 
      }
   }
}

}
}


No comments:

Post a Comment