Skip to content

Instantly share code, notes, and snippets.

@alexjebens
Last active September 4, 2017 14:20
Show Gist options
  • Save alexjebens/3f36d12e7669a5552fc5fb58f550e979 to your computer and use it in GitHub Desktop.
Save alexjebens/3f36d12e7669a5552fc5fb58f550e979 to your computer and use it in GitHub Desktop.
param (
[String] $ResourceGroupName = ''
)
# Returns strings with status messages
[OutputType([String])]
# Connect to Azure and select the subscription to work against
$servicePrincipalConnection = Get-AutomationConnection -Name AzureRunAsConnection
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint | Out-Null
if($err)
{
throw $err
}
# If there is a specific resource group, then get all VMs in the resource group,
# otherwise get all VMs in the subscription.
$vms = Get-AzureRmVM -ResourceGroupName $ResourceGroupName
$groupedVMs = $vms | `
Group-Object -Property { $_.Tags.tier } | `
Sort-Object -Property Name -Descending
for($tier = 0; $tier -lt $groupedVMs.Length; $tier++)
{
$vmGroup = $groupedVMs[$tier]
$anyStopped = $false
foreach($vmInfo in $vmGroup.Group)
{
$vm = Get-AzureRmVM `
-Status `
-ResourceGroupName $vmInfo.ResourceGroupName `
-Name $vmInfo.Name
if(($vm.Statuses | `
Select-Object -ExpandProperty Code | `
? { $_.StartsWith("PowerState") }).Substring(11) -ne 'deallocated')
{
Write-Output "Stopping VM $($vm.Name)."
Stop-AzureRmVM -ResourceGroupName $vmInfo.ResourceGroupName -Name $vmInfo.Name -Force
$anyStopped = $true
} else {
Write-Output "VM $($vm.Name) already stopped."
}
}
# If !$anyStopped there is no need to pause as the machines were already stopped
# If $group -gt $groupedVMs.Length then this is the last group, no need to pause
if($anyStopped -and ($tier -lt $groupedVMs.Length))
{
$secondsToWait = [int]::Parse($vmGroup.Group[0].Tags.tierShutdownTimeoutSeconds)
Write-Output "Tier $tier stopped. Waiting $secondsToWait seconds."
Start-Sleep -Seconds $secondsToWait
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment