Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / containers / virtual-machine

Controlling Azure Virtual Machines from PowerShell

1.00/5 (1 vote)
10 Feb 2020CPOL2 min read 2.1K  
Windows Azure portal has the full breadth of Azure visually displayed for you to see your Azure subscription and discover new things on the platform. But manually clicking through to provision a new VM or restart a VM isn’t the dream.

The Windows Azure portal is a great resource. It has the full breadth of Azure visually displayed for you to see your Azure subscription and discover new things on the platform. But manually clicking through to provision a new VM or restart a VM isn’t the dream. As much as I think it’s well designed and easy enough to use, when I want to power down a Virtual Machine, I don’t want to have to wait to login to Azure, wait for it to load, find the correct screen and finally click on the action that I need. I want it NOW!

Enter Automation

I have several Virtual Machines provisioned in Azure, mostly for testing/demonstrating purposes. Turning them on and off should be as easy as flipping a switch (or at least flipping a script).

I’m running Windows 10, which comes with PowerShell 3.0.

If you haven’t already, you will need to allow the execution of scripts in PowerShell with the following command in a PowerShell command prompt.

PowerShell
Set-ExecutionPolicy -ExecutionPolicy Unrestricted

Select Yes when asked if you’re sure.

Next, we’re going to install the Azure Resource Manager Module from the PowerShell Gallery.

AzureRM Module

You can do this in a PowerShell Command Prompt with the following:

PowerShell
Install-Module AzureRM

Now Import all the modules into this session:

PowerShell
Import-Module AzureRM

Now you can login to your Azure subscription using:

PowerShell
Login-AzureRmAccount

This brings up the Azure login prompt, I will do another post on how to setup login without having to enter your username & password. For now enter your Azure credentials as you would normally to login to the Azure Portal.

It will display all the Subscriptions you have on that account/email address.

Sweet, so this is the base to begin all your automation actions.

Display Virtual Machine Information

PowerShell
$resourceGroupName = "test-application"
$vmName = "test01"
Get-AzureRmVM -ResourceGroupName $resourceGroupName -Name $vmName

Stopping Virtual Machine

It’s important to remember to stop the Azure Virtual Machine via this powershell command or in the Azure portal. If you only shutdown the VM from within the VM, you will continue to incur charges from Microsoft.

PowerShell
Stop-AzureRmVM -ResourceGroupName $resourceGroupName -Name $vmName

Starting Virtual Machine

PowerShell
Start-AzureRmVM -ResourceGroupName $resourceGroupName -Name $vmName

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)