Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tikluganguly
Created October 17, 2016 10:37
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/8ca203628d437d6e0b0dceff2c2ba1d0 to your computer and use it in GitHub Desktop.
Save tikluganguly/8ca203628d437d6e0b0dceff2c2ba1d0 to your computer and use it in GitHub Desktop.
<#
.SYNOPSIS
Provides an option to startup selected VMs
.DESCRIPTION
This runbook can be used for starting up 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 start
.EXAMPLE
Startup-VM -connectionName "AzureRunAsConnection" -vmNames "testvm,testvm2"
.NOTES
Author: Tiklu Ganguly
Last Updated: 10/17/2016
#>
workflow Startup-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 "Starting $($vm.Name)"
$stat=$vm|Start-AzureRmVM
if($stat.IsSuccessStatusCode)
{
Write-Output "Started $($vm.Name)"
}
else
{
Write-Output "Unable to Start $($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