Skip to content

Instantly share code, notes, and snippets.

@tikluganguly
Created October 17, 2016 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tikluganguly/a8cdc89530f8a446efdafb4b97d0904c to your computer and use it in GitHub Desktop.
Save tikluganguly/a8cdc89530f8a446efdafb4b97d0904c to your computer and use it in GitHub Desktop.
<#
.SYNOPSIS
Provides an option to shutdown selected VMs
.DESCRIPTION
This runbook can be used for shutting down a set of Azure RM VMs mentioned in the parameter
.PARAMETER connectionName
String value for Azure Runbook Connection Name. The default value of this should be AzureRunAsConnection
.PARAMETER vmNames
String value for a comma separated list of vm names to shutdown
.EXAMPLE
Shutdown-VM -connectionName "AzureRunAsConnection" -vmNames "testvm,testvm2"
.NOTES
Author: Tiklu Ganguly
Last Updated: 10/17/2016
#>
workflow Shutdown-VM
{
param
(
[parameter(Mandatory=$false)]
[String]$connectionName = "AzureRunAsConnection",
[parameter(Mandatory=$true)]
[String]$vmNames
)
$currentTime = (Get-Date).ToUniversalTime()
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
}
}
try
{
$vms = Get-AzureRmVM
ForEach($vm in $vms)
{
if($vmNames -match $vm.Name)
{
Write-Output "Stopping $($vm.Name)"
$stat=$vm|Stop-AzureRmVM -Force #Start-AzureRmVM
if($stat.IsSuccessStatusCode)
{
Write-Output "Stopped $($vm.Name)"
}
else
{
Write-Output "Unable to Stop $($vm.Name) for $($stat.ReasonPhrase)"
}
}
}
}
catch
{
$errorMessage = $_.Exception.Message
Write-Error -Message "Unexpected error $errorMessage"
throw $_.Exception
}
finally
{
Write-Output "Runbook finished (Duration: $(("{0:hh\:mm\:ss}" -f ((Get-Date).ToUniversalTime() - $currentTime))))"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment