Last active
June 8, 2017 12:50
-
-
Save alexjebens/579b276cc9b9c1fa5e190670a98d97bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
for($tier = 0; $tier -lt $groupedVMs.Length; $tier++) | |
{ | |
$vmGroup = $groupedVMs[$tier] | |
$anyStarted = $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 'running') | |
{ | |
Write-Output "Starting $($vm.Name)" | |
Start-AzureRmVM -ResourceGroupName $vmInfo.ResourceGroupName -Name $vmInfo.Name | |
$anyStarted = $true | |
} | |
} | |
# If !$anystarted there is no need to pause as the machines were already running | |
# If $group -gt $groupedVMs.Length then this is the last group, no need to pause | |
if($anyStarted -and ($tier -lt $groupedVMs.Length)) | |
{ | |
$secondsToWait = [int]::Parse($vmGroup.Group[0].Tags.tierStartupTimeoutSeconds) | |
Write-Output 'Tier $tier started. 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