Skip to content

Instantly share code, notes, and snippets.

@fabiocannas
Last active October 4, 2022 07:46
Show Gist options
  • Save fabiocannas/d4fb3e9468c992c1ef3f86e0f6db7ad7 to your computer and use it in GitHub Desktop.
Save fabiocannas/d4fb3e9468c992c1ef3f86e0f6db7ad7 to your computer and use it in GitHub Desktop.
This script allows to upscale/downscale an Azure Virtual Machine. Credits to Wojciech Lepczyński (https://lepczynski.it/en/azure_en/automatic-azure-vm-resizing/). Changes: update from AzureRM to Az.
[CmdletBinding()]
param(
[Parameter(Mandatory=$True)]
[String] $VMName = "VMName",
[Parameter(Mandatory=$True)]
[String] $ResourceGroupName = "ResourceGroupName",
[Parameter(Mandatory=$True)]
[String] $Size = "VMSize"
)
# Keep track of time
$StartDate=(GET-DATE)
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection"
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzAccount `
-ServicePrincipal `
-Tenant $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
}
else
{
Write-Error -Message $_.Exception.Message
throw $_.Exception
}
}
try{
$VirtualMachine = Get-AzVM -Name $VMName -ResourceGroupName $ResourceGroupName -Status
if (!$VirtualMachine)
{
Write-Error "$($VMName) not found in $($ResourceGroupName)"
return
}
$VMStats = $VirtualMachine.Statuses
$VMStats= ($VMStats | Where Code -Like 'PowerState/*')[0].DisplayStatus
# if VM is running, execute the script
if ($VMStats -eq "VM running")
{
$vm = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMname -Status
$vm = $vm.Statuses.DisplayStatus | Select-String -Pattern "VM running"
# if the machine you want to resize has "running" state, run the script
if($vm -match "VM running")
{
$vm1 = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMname
$oldVMSize = $vm1.HardwareProfile.VmSize
$vm1.HardwareProfile.VmSize = $Size
Update-AzVM -VM $vm1 -ResourceGroupName $ResourceGroupName
Write-Output "Changed $($VMName) vm size from $($oldVMSize) to $($Size)"
}
else{
Write-Error "Cannot upscale/downscale VM $($VMName) while the status is $($vm)"
}
}else{
Write-Error "Cannot upscale/downscale VM $($VMName) while the status is $($VMStats)"
}
# Show when finished
$Duration = NEW-TIMESPAN –Start $StartDate –End (GET-DATE)
Write-Output "Done in $([int]$Duration.TotalMinutes) minute(s) and $([int]$Duration.Seconds) second(s)"
}
catch{
Write-Error -Message $_.Exception.Message
throw $_.Exception
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment