-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathStart.ps1
85 lines (76 loc) · 2.41 KB
/
Start.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
Param(
$AutomationRG = "My1StRG",
$AutomationAcct = "StopStart",
$StartType = "Auto"
)
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-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
}
}
function Get-AzureRmVMStatus {
[CmdletBinding()]
param (
#The name of a resouce group in your subscription
[Parameter(Mandatory=$true)]
[string]
$ResourceGroupName
,
#VM name filter
[Parameter()]
[string]
$Name = '*'
)
Get-AzureRmVM -ResourceGroupName $ResourceGroupName | ? {$_.Tags.Keys -eq "Start" -and $_.Tags.Values -eq "$StartType"} |
Get-AzureRmVM -Status |
Select-Object -Property Name, Statuses, ResourceGroupName |
Where-Object {$_.Name -like $Name} |
ForEach-Object {
$VMName = $_.Name
$ResourceGroupName = $_.ResourceGroupName
$_.Statuses |
Where-Object {$_.Code -like 'PowerState/*'} |
ForEach-Object {
New-Object -TypeName psobject -Property @{
Name = $VMName
ResourceGroupName = $ResourceGroupName
Status = $_.DisplayStatus
}
}
}
}
$subs = Get-AzureRmSubscription -WarningAction SilentlyContinue
$subs | % {Select-AzureRmSubscription -SubscriptionId $_.SubscriptionId
$VMs = Get-AzureRmResourceGroup | % {Get-AzureRmVMStatus $_.ResourceGroupName}
$ASVMs = $VMs | ? {$_.Status -eq "VM deallocated"}
Foreach ($ASVM in $ASVMs)
{
$params = @{"Name"=$ASVM.name;"ResourceGroupName"=$ASVM.ResourceGroupName}
$msg = "Starting VM "
$msg += $ASVM.name
$msg += " on resouregroup "
$msg += $ASVM.ResourceGroupName
$msg += "......"
Write-Output " "
Write-Output $msg
Write-Output " "
Start-AzureRmAutomationRunbook -AutomationAccountName $AutomationAcct -Name "StartVM" -Parameters $params -ResourceGroupName $AutomationRG
}
}