Start and Stop Azure VM with Azure Automation

Page content

Last week I updated my Azure storage and Virtual machines to Azure Resource Manager. Before that I had the OneShare for MSDN app from Sogeti to start and stop my VM every day so I could start using it without having it to boot manually. Unfortunately the app cannot authenticate with Azure Resource Manager so I have to find another way to make it automatically start and stop.

Azure Automation

The first thing I thought of was Azure Automation, I use that a lot and I have the knowledge of PowerShell to make this happen. I started with creating an Azure Automation resource. While creating this resource I noticed a new option called ‘Create Azure Run As account’. This option creates a service principal in your Azure Active Directory and gives it Contributor rights at the subscription level.

This service principal is a certificate and a connection of the type ‘AzureServicePrincipal’. With this option you do not need to create a separate account with password to run the scripts.

Also new is that you get two tutorial runbooks after creating the Automation resource to get you started.

  • AzureAutomationTutorial (Graphical Runbook)
  • AzureAutomationTutorialScript (PowerShell Runbook)

Creating the script

The goal for me is to start and stop the VM and preset times. I could create two scripts with each a schedule or just one script with two schedules and a parameter to start of stop. I choose the latest option, just one script with a parameter. I started with the ‘AzureAutomationTutorialScript’ as an example because I never used the service principal before. It is a very simple way to connect to Azure with just three lines of code

After I saw that I created a new Runbook of the type ‘PowerShell Runbook’ and added these three lines of code, the command to get the current status and depending on the parameter the command to start or stop the VM. See full the script below.


Now that the script is done we can add the schedule to the script to really automate it. This can be done from the runbook blade by clicking on ‘Schedules’. Click an ‘Add a schedule’ to create a new one and it will ask you to create the schedule and configure the parameters for the script.


I really like the two tutorial scripts to get you started, I sometimes struggle to get started with something new and this will give a nice starting point. I found it hard to find the correct code to get the current status of the VM. You need to add the ‘-Status’ when you get the VM. In the statuses that you get back you need to find the status code ‘PowerState’ and from the property ‘DisplayStatus’ you know if the VM is running or not.