Last active
February 28, 2019 08:18
-
-
Save prombouts/43f14670739bab51834bd3753c8c89f7 to your computer and use it in GitHub Desktop.
This PowerShell Workflow runbook connects to Azure using an Automation Credential and Starts/Stops a VM/a list of VMs/All VMs in a Subscription in-parallel.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Workflow Stop-Start-AzureVM-By-Tag | |
{ | |
Param | |
( | |
[Parameter(Mandatory=$true)][ValidateSet("Start","Stop")] | |
[String] | |
$Action, | |
[Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()] | |
[String] | |
$TagName="ScheduledOnOff", | |
[Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()] | |
[String] | |
$TagValue="Yes" | |
) | |
Write-Output "Logging in to Azure..." | |
$servicePrincipalConnection = Get-AutomationConnection -Name "AzureRunAsConnection" | |
$connectionResult = Connect-AzureRmAccount ` | |
-ServicePrincipal ` | |
-TenantId $servicePrincipalConnection.TenantId ` | |
-ApplicationId $servicePrincipalConnection.ApplicationId ` | |
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint | |
Write-Output "Logging in to Azure succeeded" | |
try | |
{ | |
$AzureVMNames = (Get-AzureRmVM | ? {$_.Tags[$TagName] -eq $TagValue}).Name | |
[System.Collections.ArrayList]$AzureVMs = $AzureVMNames | |
Write-Output "Looping all VM names"; | |
foreach -parallel ($AzureVM in $AzureVMs) | |
{ | |
Write-Output "($Action) VM ($AzureVM)..."; | |
if($Action -eq "Stop") | |
{ | |
Get-AzureRmVM | ? {$_.Name -eq $AzureVM} | Stop-AzureRmVM -Force | |
} | |
else | |
{ | |
Get-AzureRmVM | ? {$_.Name -eq $AzureVM} | Start-AzureRmVM | |
} | |
Write-Output "($Action) VM ($AzureVM) done"; | |
} | |
} | |
catch { | |
Write-Output "Looping all VM names: Got error ($_.Exception.Message)" | |
} | |
try | |
{ | |
$AzureVMssNames = (Get-AzureRmVmss | ? {$_.Tags[$TagName] -eq $TagValue}).Name | |
[System.Collections.ArrayList]$AzureVMScaleSets = $AzureVMssNames | |
Write-Output "Looping all VM ScaleSet names"; | |
foreach -parallel ($AzureVMScaleSet in $AzureVMScaleSets) | |
{ | |
Write-Output "($Action) VM ($AzureVMScaleSet)..."; | |
if($Action -eq "Stop") | |
{ | |
Get-AzureRmVmss | ? {$_.Name -eq $AzureVMScaleSet} | Stop-AzureRmVmss -Force | |
} | |
else | |
{ | |
Get-AzureRmVmss | ? {$_.Name -eq $AzureVMScaleSet} | Start-AzureRmVmss | |
} | |
Write-Output "($Action) VM ($AzureVMScaleSet) done"; | |
} | |
} | |
catch { | |
Write-Output "Looping all VM ScaleSet names: Got error ($_.Exception.Message)" | |
} | |
Write-Output "Script completed" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment