I have a small lab setup within Azure and over the past week I have been working quite a bit within that lab perfecting a couple of PowerShell scripts.
As I have limited credits available to me within Azure I am always careful to ensure that my Virtual Machines (VMs) are only running when I need them and de-allocated when I am not using them. Having to sign in to the Azure Portal to start the VMs and then do the same to de-allocate can be slightly cumbersome and time consuming, so I've investigated a quicker way in doing this via PowerShell cmdlets.
The first step in connecting to Azure via PowerShell is installing the necessary modules from the PowerShell Gallery, the following commands will allow this:
**Install the Azure Resource Manager modules from the PowerShell Gallery
Install-Module AzureRM -Force
**Install the Azure Service Management module from the PowerShell Gallery
Install-Module Azure -Force
Adding "Force" to the end of both commands ensures that any version you currently have installed is overwritten with the latest version that is available on the PowerShell Gallery.
The next step is to login to your Azure account, this can be done with a simple command:
**Login into Azure Account
This command launches a pop up box that asks for your credentials. Once you have logged into your account the next step is to select the relevant subscription where your VMs live. I have several subscriptions attached to my account so I found using the command below helped me to identify which one was my active one:
Once you've identified which subscription you wish to connect to and interact with you need to select that. In order to do so you need to issue the command below:
**Select Active subscription
Set-AzureRMContext -SubscriptionId "123456af-78dd-9123-b45c-678ca9c1e234"
The above SubscriptionID is just a dummy entry, you can locate your relevant ID from the output you received from the Get-AzureRMSubscription command.
In order to start or stop your VMs from PowerShell you need to be able to provide the Resource Group that the VMs reside within and the VMs name. This simple command will give you an output with this information:
**Get information regarding VMs and resource group
Now that you have that information the next step is to start or stop one of your VMs. The following commands can help with this:
Start-AzureRMVM -ResourceGroupName "VMResourceGrp" -Name "Server1"
Stop-AzureRMVM -ResourceGroupName "VMResourceGrp" -Name "Server1"
Substituting the resource group name and server names as appropriate.