-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStartStopVMs.ps1
66 lines (61 loc) · 1.93 KB
/
StartStopVMs.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
Param
(
[Parameter(Mandatory=$false)]
[String] $startstop
)
Import-Module Az.Accounts
Import-Module Az.Automation
Import-Module Az.Compute
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Connect-AzAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
Write-Output "Starting task"
if($startstop -eq "start"){
Write-Output "StartVM task initiated"
$vms = Get-AzVM -Status
foreach($vm in $vms){
$vmname = $vm.Name
$vmrg = $vm.ResourceGroupName
Write-Output "Starting $vmname"
Start-AzVM -ResourceGroupName $vmrg -Name $vmname
while($vmstate -ne "VM running"){
$vmstate = (Get-AzVM -Status -ResourceGroupName $vmrg -Name $vmname).Statuses.DisplayStatus[1]
Start-Sleep -s 5
}
Write-Output "Started $vmname"
}
}
if($startstop -eq "stop"){
Write-Output "StopVM task initiated"
$vms = Get-AzVM -Status | where {$_.Name -like "*DOPS*"}
foreach($vm in $vms){
$vmname = $vm.Name
$vmrg = $vm.ResourceGroupName
Write-Output "Stopping $vmname"
Stop-AzVM -ResourceGroupName $vmrg -Name $vmname -Force
while($vmstate -ne "VM deallocated"){
$vmstate = (Get-AzVM -Status -ResourceGroupName $vmrg -Name $vmname).Statuses.DisplayStatus[1]
Start-Sleep -s 5
}
Write-Output "Stopped $vmname"
}
}