-
Notifications
You must be signed in to change notification settings - Fork 1
/
Start-AzureVMs.ps1
269 lines (220 loc) · 13.1 KB
/
Start-AzureVMs.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
<#
.SYNOPSIS
Invokes Start-AzureVM for each virtual machine matching a -like or -match pattern. Intended to be run from Azure Automation.
.PARAMETER CredentialName
The name of the credential stored in the Azure Automation assets library.
.PARAMETER SubscriptionId
The Id of the subscription within which to retrieve (Get-Azure(RM)VM) and shutdown (Stop-Azure(RM)VM) Azure Virtual Machines.
.PARAMETER VirtualMachinePattern
Accepts a string with wildcard characters, to be fed to a -like statement.
OR if also specifying isVirtualMachinePatternRegex = $true, accepts a regex pattern.
.PARAMETER isVirtualMachinePatternRegex
Accepts $true or $false to determine whether VirtualMachinePattern takes a -like compatible, or -match (regex) compatible match string.
.PARAMETER PriorityVMsList
Allows you to provide a list of VM ServiceNames (!important!) that should be booted SleepIntervalMinutes ahead of all other VMs matching the pattern.
.PARAMETER SleepIntervalMinutes
Provide an integer that will be used as the amount of time to sleep between booting the PriorityVMsList and all other VirtualMachinePattern matching VMs.
.PARAMETER DontStartOnWeekends
$true or $false as to whether the script should start on 'Saturday' or 'Sunday. This has only been tested for all-English environments. This is to allow for the lack of granularity in the 'daily' schedule in Azure Automation which doesn't allow for removing some days from the 'daily' list.
.PARAMETER AzureClassic
If $true, the script will use the classic (non-Resource Manager/RM/ARM) cmdlets for Azure Classic VMs.
.EXAMPLE
The workflow is unlikely to ever be run like this, but this gives you an idea of how to fill out the parameters when prompted by Azure Automation.
Start-AzureVM.ps1 -CredentialName "Azure Automation Unattended account" -Subscription "Ashley Azure" -VirtualMachinePattern "azurevm-*" -PriorityVMsList "azurevm-dc01,azurevm-dc02" -SleepIntervalMinutes 10 -DontStartOnWeekends:$true
.EXAMPLE
The workflow is unlikely to ever be run like this, but this gives you an idea of how to fill out the parameters when prompted by Azure Automation.
Start-AzureVM.ps1 -CredentialName "Azure Automation Unattended account" -Subscription "Ashley Azure" -isVirtualMachinePatternRegex:$true -VirtualMachinePattern "^(!?azurevm-retired$)azurevm-.+$" -PriorityVMsList "azurevm-dc01,azurevm-dc02" -SleepIntervalMinutes 10 -DontStartOnWeekends:$true
.NOTES
Author: ashley.geek.nz
Version: 2017-02-08 12:28 GMT
Github: https://github.com/webash/azure-automation/
The credential stored in the asset library within Azure Automation will need the permission (Virtual Machine contributor or higher) within the subscription in order to start VMs.
See Start-AzureVMs.ps1 in the same https://github.com/webash/azure-automation/ repository to _start_ VMs too.
.LINK
https://ashley.geek.nz/2016/03/31/using-azure-automation-to-stop-and-start-azure-iaas-virtual-machines/
#>
workflow Start-AzureVMs
{
param (
[parameter(Mandatory=$true)]
[string]$CredentialName,
[parameter(Mandatory=$true)]
[string]$SubscriptionId,
# Help for how I end up using my Regex to _not_ match some VMs:
# http://stackoverflow.com/a/2601318/443588
# ^(?!azurevm-sync01$)(?!azurevm-sync03$)azurevm-.+$
[parameter(Mandatory=$true)]
[string]$VirtualMachinePattern,
[bool]$isVirtualMachinePatternRegex = $false,
[string]$PriorityVMsList,
[int]$SleepIntervalMinutes = 5,
[bool]$DontStartOnWeekends = $false,
[parameter(Mandatory=$false)]
[bool]$AzureClassic = $false
)
<#
function Filter-VMs {
param (
$VMs
)
if ( $Using:isVirtualMachinePatternRegex ) {
return $VMs | Where-Object -filterScript { ($_.Name -match $Using:VirtualMachinePattern -and -not ($Using:PriorityVMsList -contains $_.Name)) }
} else {
return $VMs | Where-Object -filterScript { ($_.Name -like $Using:VirtualMachinePattern -and -not ($Using:PriorityVMsList -contains $_.Name)) }
}
}
#>
Write-Output ( [string]::Format("----- Script Start {0} -----", (Get-Date).toString() ))
if ( $AzureClassic ) {
Write-Output "Azure VM Classic cmdlets will be used for this session because -AzureClassic is true"
}
Write-Output "Using credential named $CredentialName"
$credential = Get-AutomationPSCredential -Name $CredentialName
if ( -not $AzureClassic ) {
Login-AzureRmAccount -SubscriptionId $SubscriptionId -Credential $credential -ErrorAction Stop
#Write-Output( [string]::Format("`t{0}, {1}\{2} in tenant {3}", $Account.Context.Account.Id, $Account.Context.Subscription.SubscriptionId, $Account.Context.Subscription.SubscriptionName, $Account.Context.Subscription.TenantId ))
} else {
Add-AzureAccount -Credential $credential -ErrorAction Stop
}
Write-Output "Using $subscriptionid subscription"
if ( -not $AzureClassic ) {
Select-AzureRmSubscription -SubscriptionId $SubscriptionId
#Write-Output ( [string]::Format("`t{0} ({1}) on tenant {2}", $RmSub.Subscription.SubscriptionName, $RmSub.Subscription.SubscriptionId, $RmSub.Subscription.TenantId) )
} else {
Select-AzureSubscription -SubscriptionId $SubscriptionId
}
$day = (Get-Date).DayOfWeek
if ( $DontStartOnWeekends -and ($day -eq 'Saturday' -or $day -eq 'Sunday') ) {
Write-Output ([string]::Format("-DontStartOnWeekends switch was provided, and it is {0} - script aborting", (Get-Date).toString() ))
Write-Output ([string]::Format("----- Script End {0} -----", (Get-Date).toString() ))
exit
}
if (-not $PriorityVMsList.isNullOrEmpty) {
Write-Output ([string]::Format( "Iterating Priority VMs {0}...", $PriorityVMsList ))
# Turns out a simple [string]::Split() is impossible in Workflows... so had to pass through to an InlineScript for proper PowerShell to take over.
#$PriorityVMs = $PriorityVMsList | select-string -pattern '[^,]+' -AllMatches
$PriorityVMs = $null
$PriorityVMs = InlineScript { $PriorityVMs = ($Using:PriorityVMsList).Split(','); $PriorityVMs }
$PriorityVMs | Foreach-Object { Write-Output "`t- $_" }
Write-Output ""
foreach($VMName in $PriorityVMs){
Write-Output ([string]::Format("Getting initial state of {0}...", $VMName))
if ( -not $AzureClassic ) {
$VM = Get-AzureRmVM | Where-Object -filterScript { $_.name -eq $VMName }
$VM | Get-AzureRmVm -Status | `
Foreach-Object { Write-Output ([string]::Format("`t{0}\{1}: {2}, {3}",`
$_.ResourceGroupName,`
$_.Name,`
(($_.StatusesText | convertfrom-json) | Where-Object -FilterScript { $_.code -like "PowerState*" }).code,`
(($_.StatusesText | convertfrom-json) | Where-Object -FilterScript { $_.code -like "PowerState*" }).displayStatus)) }
} else {
$VM = Get-AzureVM | Where-Object -filterScript { $_.name -eq $VMName }
Write-Output ([string]::Format("`tClassic\{0}: {1}, {2}", $VM.Name, $VM.PowerState, $VM.Status))
}
if ( $VM -ne $null ) {
Write-Output ([string]::Format("Starting VM {0}...", $VM.Name))
if ( -not $AzureClassic ) {
$operationOutput = $VM | Start-AzureRmVM
if ( $operationOutput.IsSuccessStatusCode ) {
Write-Output ([string]::Format("`t...{0}", $operationOutput.ReasonPhrase))
} else {
if ( $operationOutput.ReasonPhrase -ne $null ) {
Write-Error ([string]::Format("`t...Error: {0}", $operationOutput.ReasonPhrase))
} else {
Write-Error "`t...Error: <no message available, likely there is an exception notice above>"
}
}
} else {
$operationOutput = $VM | Start-AzureVM
Write-Output ([string]::Format("`t`t{0}", $operationOutput.OperationStatus))
}
if ( -not $AzureClassic ) {
$VM = Get-AzureRmVM | Where-Object -filterScript { $_.name -eq $VMName }
$VM | Get-AzureRmVm -Status | `
Foreach-Object { Write-Output ([string]::Format("`t{0}\{1}: {2}, {3}",`
$_.ResourceGroupName,`
$_.Name,`
(($_.StatusesText | convertfrom-json) | Where-Object -FilterScript { $_.code -like "PowerState*" }).code,`
(($_.StatusesText | convertfrom-json) | Where-Object -FilterScript { $_.code -like "PowerState*" }).displayStatus)) }
} else {
$VM = Get-AzureVM | Where-Object -filterScript { $_.name -eq $VMName }
Write-Output ([string]::Format("`tClassic\{0}: {1}, {2}", $VM.Name, $VM.PowerState, $VM.Status))
}
} else {
Write-Output "`t`t$VMName doesn't exist"
}
}
Write-Output "Sleeping for $SleepIntervalMinutes min to give Priority VMs chance to start-up..."
for ($i = 1; $i -le $SleepIntervalMinutes; $i++) {
Start-Sleep -Seconds 60
Write-Output "`t$i min"
}
Write-Output "Confirming new status of PriorityVMsList..."
foreach ($VMName in $PriorityVMs) {
if ( -not $AzureClassic ) {
$VM = Get-AzureRmVM | Where-Object -filterScript { $_.name -eq $VMName }
$VM | Get-AzureRmVm -Status | `
Foreach-Object { Write-Output ([string]::Format("`t{0}\{1}: {2}, {3}",`
$_.ResourceGroupName,`
$_.Name,`
(($_.StatusesText | convertfrom-json) | Where-Object -FilterScript { $_.code -like "PowerState*" }).code,`
(($_.StatusesText | convertfrom-json) | Where-Object -FilterScript { $_.code -like "PowerState*" }).displayStatus)) }
} else {
$VM = Get-AzureVM | Where-Object -filterScript { $_.name -eq $VMName }
Write-Output ([string]::Format("`tClassic\{0}: {1}, {2}", $VM.Name, $VM.PowerState, $VM.Status))
}
}
}
<#$vmFilter = { }
if ( $isVirtualMachinePatternRegex ) {
Write-Output "Using -match mode."
$vmFilter = { ($_.Name -match $VirtualMachinePattern -and -not ($PriorityVMsList -contains $_.Name)) }
} else {
Write-Output "Using -like mode."
$vmFilter = { ($_.Name -like $VirtualMachinePattern -and -not ($PriorityVMsList -contains $_.Name)) }
}#>
$vmFilter = { (($isVirtualMachinePatternRegex -and $_.Name -match $VirtualMachinePattern) -or $_.Name -like $VirtualMachinePattern) -and -not ($PriorityVMsList -contains $_.Name) }
Write-Output ([string]::Format("VirtualMachinePattern: {0}", $VirtualMachinePattern))
Write-Output "`t$vmFilter"
Write-Output "Gathering VMs matching pattern/like..."
if ( -not $AzureClassic ) {
$VMs = Get-AzureRmVM | Where-Object -filterScript { (($isVirtualMachinePatternRegex -and $_.Name -match $VirtualMachinePattern) -or $_.Name -like $VirtualMachinePattern) -and -not ($PriorityVMsList -contains $_.Name) }
$VM | Get-AzureRmVm -Status | `
Foreach-Object { Write-Output ([string]::Format("`t{0}\{1}: {2}, {3}",`
$_.ResourceGroupName,`
$_.Name,`
(($_.StatusesText | convertfrom-json) | Where-Object -FilterScript { $_.code -like "PowerState*" }).code,`
(($_.StatusesText | convertfrom-json) | Where-Object -FilterScript { $_.code -like "PowerState*" }).displayStatus)) }
} else {
$VMs = Get-AzureVM | Where-Object -filterScript { (($isVirtualMachinePatternRegex -and $_.Name -match $VirtualMachinePattern) -or $_.Name -like $VirtualMachinePattern) -and -not ($PriorityVMsList -contains $_.Name) }
$VMs | Foreach-Object { Write-Output ([string]::Format("`tClassic\{0}: {1}, {2}", $_.Name, $_.PowerState, $_.Status)) }
}
Write-Output "Starting pattern-matched VMs in parallel..."
ForEach -Parallel ($VM in $VMs){
Write-Output ([string]::Format("`tStarting VM {0}...", $VM.Name))
if ( -not $AzureClassic ) {
$parallelOperationOutput = $VM | Start-AzureRmVM
if ( $parallelOperationOutput.IsSuccessStatusCode ) {
Write-Output ([string]::Format("`t{0}\{1}: {2}", $VM.ResourceGroupName, $VM.Name, $parallelOperationOutput.ReasonPhrase))
} else {
Write-Error ([string]::Format("`t{0}\{1} error: {2}", $VM.ResourceGroupName, $VM.Name, $parallelOperationOutput.ReasonPhrase))
}
} else {
$parallelOperationOutput = $VM | Start-AzureVM
Write-Output ([string]::Format("`tClassic\{0}: {1}", $VM.Name, $parallelOperationOutput.OperationStatus))
}
}
Write-Output "Confirming new status of VMs with Name -like/-match $VirtualMachineLike"
if ( -not $AzureClassic ) {
Get-AzureRmVM | Get-AzureRmVm -Status | Where-Object -FilterScript { (($isVirtualMachinePatternRegex -and $_.Name -match $VirtualMachinePattern) -or $_.Name -like $VirtualMachinePattern) -and -not ($PriorityVMsList -contains $_.Name) } |`
Foreach-Object { Write-Output ([string]::Format("`t{0}\{1}: {2}, {3}",`
$_.ResourceGroupName,`
$_.Name,`
(($_.StatusesText | convertfrom-json) | Where-Object -FilterScript { $_.code -like "PowerState*" }).code,`
(($_.StatusesText | convertfrom-json) | Where-Object -FilterScript { $_.code -like "PowerState*" }).displayStatus)) }
} else {
Get-AzureVM | Where-Object -FilterScript { (($isVirtualMachinePatternRegex -and $_.Name -match $VirtualMachinePattern) -or $_.Name -like $VirtualMachinePattern) -and -not ($PriorityVMsList -contains $_.Name) } | `
Foreach-Object { Write-Output ([string]::Format("`tClassic\{0}: {1}, {2}", $_.Name, $_.PowerState, $_.Status)) }
}
Write-Output ( [string]::Format("----- Script Stop {0} -----", (Get-Date).toString() ))
}