Shutting down your Azure VMs automatically

rwagg-white small

Rob Waggoner

MS-Azure_rgb_Blk

I’ve talked about the ability to schedule the shutdown and restart of your VMs in Azure and I wanted to share some detail on how to do that.  While this script could get much more complex, here are some of the basics.

First be sure to install PowerShell for Microsoft Azure here.  The complete SDK download page is here if you want to download the other tools too. 

Now for the PowerShell commands (or you can make this a script):

# Get-AzureSubscription will ask you to save the publishsettings file. 
# You only need to do this once, then you can reference the
# publishsettings file if you are using a script. 
Get-AzureSubscription

# Change the path of the Import-AzurePublishSettingsFile to the
# same name and path you used above.
Import-AzurePublishSettingsFile "C:\Azure Scripts\credentials for shutdown\Windows Azure MSDN - Visual Studio Ultimate-9-30-2014-credentials.publishsettings"

#I've chosen my MSDN subscription, change to your subscription name
Select-AzureSubscription -SubscriptionName "Windows Azure MSDN - Visual Studio Ultimate"

# This will enumerate all of the available VMs
Get-AzureVM | Stop-AzureVM –Force

Get-AzureSubscription will prompt you to sign into your Azure account and then prompt you to save your credentials to your local machine.  These credentials will be used in the second command Import-AzurePublishSettingsFile to import the Azure credentials into your PowerShell session.

Select-AzureSubscription will choose the actual subscription that contains your VMs, I added this command in case you manage multiple subscriptions.  

The last commands enumerate all of your VMs (Get-AzureVM) and sends the list of the VMs to the Stop-AzureVM cmdlet to do the actual shut down.  The –Force parameter ensures the VM is deallocated once its shut down.  Remember that the VM must be deallocated or you will continue to be charged the runtime costs.

As far as starting your VMs…  Again, the simple version is the same script as above, but replace the last line (Get-AzureVM | Stop-AzureVM –Force) with

Get-AzureVM | Start-AzureVM

 

Until next time,

Rob