-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathShutdownTaggedVMs
More file actions
32 lines (26 loc) · 1.42 KB
/
ShutdownTaggedVMs
File metadata and controls
32 lines (26 loc) · 1.42 KB
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
#Set variables
$Shutdown = $true
# get automation variables
$tagName = Get-AutomationVariable -Name 'shutdownResourceTagName'
$tagValue = Get-AutomationVariable -Name 'shutdownResourceTagValue'
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Add-AzureRMAccount -ServicePrincipal -Tenant $Conn.TenantID `
-ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
#Shutdown machines
$taggedResources = Find-AzureRmResource -TagName $tagName -TagValue $tagValue
$targetVms = $taggedResources | Where-Object{$_.ResourceType -eq "Microsoft.Compute/virtualMachines"} | select resourcegroupname, name | Get-AzureRmVM -status
ForEach ($vm in $targetVms)
{
$currentpowerstatus = $vm |select -ExpandProperty Statuses | Where-Object{ $_.Code -match "PowerState" } | select Code, DisplayStatus
if($Shutdown -and $currentpowerstatus.Code -eq "PowerState/running"){
Write-Output "Stopping $($vm.Name)";
Stop-AzureRmVm -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Force;
}
elseif($Shutdown -eq $false -and $currentpowerstatus.Code -ne "PowerState/running"){
Write-Output "Starting $($vm.Name)";
Start-AzureRmVm -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName;
}
else {
Write-Output "VM $($vm.Name) is already in desired state : $($currentpowerstatus.DisplayStatus)";
}
}