Last active
April 20, 2018 21:28
-
-
Save timothywarner/6a9717e2f136bbbaf5675333f59c2d43 to your computer and use it in GitHub Desktop.
Reset-AzureRMVM - Use with Azure Automation runbook to schedule VM startup and shutdown.
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 Reset-AzureRmVM | |
{ | |
Param | |
( | |
[Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()] | |
[String] | |
$AzureSubscriptionId='', | |
[Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()] | |
[String] | |
$AzureVMList='', | |
[Parameter(Mandatory=$true)][ValidateSet("Start","Stop")] | |
[String] | |
$Action | |
) | |
$connectionName = "AzureRunAsConnection" | |
try | |
{ | |
# Get the connection "AzureRunAsConnection " | |
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName | |
"Logging in to Azure..." | |
Connect-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 | |
} | |
} | |
if($AzureVMList -ne "All") | |
{ | |
$AzureVMs = $AzureVMList.Split(",") | |
[System.Collections.ArrayList]$AzureVMsToHandle = $AzureVMs | |
} | |
else | |
{ | |
$AzureVMs = (Get-AzureRmVM).Name | |
[System.Collections.ArrayList]$AzureVMsToHandle = $AzureVMs | |
} | |
foreach($AzureVM in $AzureVMsToHandle) | |
{ | |
if(!(Get-AzureRmVM | Where-Object {$_.Name -eq $AzureVM})) | |
{ | |
throw " AzureVM : [$AzureVM] - Does not exist! - Check your inputs " | |
} | |
} | |
if($Action -eq "Stop") | |
{ | |
Write-Output "Stopping VMs"; | |
foreach -parallel ($AzureVM in $AzureVMsToHandle) | |
{ | |
Get-AzureRmVM | Where-Object {$_.Name -eq $AzureVM} | Stop-AzureRmVM -Force | |
} | |
} | |
else | |
{ | |
Write-Output "Starting VMs"; | |
foreach -parallel ($AzureVM in $AzureVMsToHandle) | |
{ | |
Get-AzureRmVM | Where-Object {$_.Name -eq $AzureVM} | Start-AzureRmVM | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment