Azure PowerShell Start Virtual Machine

This is the script I use to start virtual machines in our cloud environment. I write it down here for archive and sharing purposes.

1.png

It is based on the Azure RunAs automation account.

The only thing thing you need to do is to schedule this script daily.


<#
    .DESCRIPTION
        Turns of virtual machines only office days.

    .NOTES
        AUTHOR: Michele Ferracin
#>


# No Sunday, no Saturday.
$wd = (Get-Date).DayOfWeek

if ($wd -eq "Sunday" -or $wd -eq "Saturday") {
 exit 0;
}

$connectionName = "AzureRunAsConnection"
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
    }
}

Start-AzureRmVM -Name "YourVM1" -ResourceGroupName "YourResourceGroup"

Start-AzureRmVM -Name "YourVM2" -ResourceGroupName "YourResourceGroup"


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s