-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAzureVM-Startup-Shutdown.ps1
64 lines (47 loc) · 1.81 KB
/
AzureVM-Startup-Shutdown.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
param(
[Parameter(Mandatory)][string]$powerMgmtTag,
[Parameter(Mandatory)][ValidateSet("Startup", "Shutdown")][string]$action
)
## Import Powershell Modules
Import-Module Az.Accounts
Import-Module Az.Compute
Import-Module Az.Resources
## Get service principal details from shared resources
$azureSpCreds = Get-AutomationPSCredential -Name ''
$tenantId = Get-AutomationVariable -Name ''
$SubId = Get-AutomationVariable -Name ''
## Disabling autosaving of Azure credentials
Disable-AzContextAutoSave
## Auth with service principal
Connect-AzAccount -ServicePrincipal -Credential $azureSpCreds -Tenant $tenantId
Set-AzContext -Subscription $SubId
$azureVMs = Get-AzResource -Tag @{ "Power Management" = $powerMgmtTag } | Where-Object -FilterScript { $_.ResourceType -eq "Microsoft.Compute/virtualMachines" }
switch ($action) {
Shutdown {
## Loop over each item and stop the VM
foreach ($azureVm in $azureVms ) {
try {
Write-Output "Shutting down $($azureVm.Name)"
Stop-AzVM -Name $azureVm.Name -ResourceGroup $azureVm.ResourceGroupName -Force
Write-Output "$($azureVm.Name) has been deallocated"
}
catch {
Write-Output "Something went wrong shutting down $($azureVm.Name)"
Write-Output $_
}
}
}
Startup {
foreach ($azureVm in $azureVms ) {
try {
Write-Output "Starting up $($azureVm.Name)"
Start-AzVM -Name $azureVm.Name -ResourceGroup $azureVm.ResourceGroupName
Write-Output "$($azureVm.Name) has been started"
}
catch {
Write-Output "Something went wrong starting up $($azureVm.Name)"
Write-Output $_
}
}
}
}