Thursday, September 14, 2017

PowerShell script sample code to auto start and shut down Azure VM in a resource management group

There are quite a lot of changes in RMVM access API in the last two years. Here is some sample code which works well at the moment (2017-09-14).

Hopefully they can save you some time.



1. Install AzureRM module

script: Install-Module -Name AzureRM

2. Check PowerShell version and AzureRM module version

script: $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      14393  1715

script: (get-module azurerm).Version

Major  Minor  Build  Revision
-----  -----  -----  --------
4      3      1      -1

3. Import AzureRM module

script: Import-Module AzureRM

4. Log in without prompt window

First we need to create a file to store the context information.

Login-AzureRmAccount

$Global:_ContextFilePath = "c:\azure.user.ericfang@outlook.com.ctx"
Save-AzureRmContext -Path $Global:_ContextFilePath -Force 

Then we can import the context file to avoid input user name and password manually.

Import-AzureRmContext -Path $Global:_ContextFilePath

5. Get the RM VM

$vmname = 'vm name'
$VMDetail = Get-AzureRmVM -ResourceGroupName $ResourceGroupName -Name $VmName -Status | Select-Object -ExpandProperty StatusesText | convertfrom-json
$vmPowerstate = $VMDetail[1].Code

6. Start VM

if ($vmPowerstate -like "PowerState/running"){
write-host "VM '$vmname' is ""$vmPowerstate"". Skip."
}
else{
write-host "Starting VM '$vmname'"
Start-AzureRMVM -ResourceGroupName $ResourceGroupName -Name $VmName -Verbose
}

7. Or, shut it down (deallocate it)

if ($vm.PowerState -like "PowerState/running"){
write-host "Stopping VM '$vmname'"
Stop-AzureRMVM -ResourceGroupName $ResourceGroupName -Name $VmName -Verbose -Force
}
else{
write-host "VM '$vmname' is ""$vmPowerstate"". Skip."
}

Done.

PS: I scheduled the script in windows task scheduler to shut down all dev VMs in the evening. That can save a lot in case I forgot to shut them down manually.

PS 2:

Below is the script to start or stop classic Azure VM.

Import-Module "C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1"

# Get-AzurePublishSettingsFile

$publishsettings = 'e:\EricFang\Visual Studio Ultimate with MSDN-9-16-2016-credentials.publishsettings'

write-host "AzureSubscription: "
Import-AzurePublishSettingsFile $publishsettings

Select-AzureSubscription -SubscriptionId "YOUR SUBSCRIPTION GUID STRING"

$vmname = 'hvEF4'
$vm = Get-AzureVM | Where-Object { $_.Name -eq $vmname }
write-host "AzureVM: "
$vm | fl *

if ($vm.PowerState -eq "Started"){
write-host "VM '$vmname' is ""$($vm.PowerState)"". Skip."
}
else{
write-host "Starting VM '$vmname'"
$vm | Start-AzureVM
}

# $vm | Stop-AzureVM -Force

write-host "done."

No comments:

Post a Comment