The Azure Code Samples are currently available in English

How to optimize costs by setting expired date for Azure Virtual Machine by PowerShell

Por One Code
Última atualização: 13/02/2017
Editar no GitHub


This script demonstrates how to set expired date for Azure Virtual Machine in Dev Labs by PowerShell.

Related topics


Practically, developers often create Azure Virtual Machines in Dev Labs for demo or development purpose, while those “test” VM instances are also charged by the company. Since nobody remembers to delete them after development, company will have to pay for the instances. Thus, it must be so wonderful to have “test” VM instances automatically deleted.

Luckily, Microsoft Azure has released new features about expired date of virtual machine on October 6, 2016. IT pro can make the use of this new feature to optimize costs. Besides, this sample also supplies an OOB script to set expired date for your existed VM instance in Dev Labs.


Run this sample

  • Open the script file SetExpiredDateAzureVM.ps1
  • Edit the parameter “-VMName” and “-LabName” and “-ExpiredUTCDate”
    ps1 Set-AzureVirtualMachineExpiredDate -VMName "vmname" -LabName "labname" -ExpiredUTCDate "2016-10-10"

Note: the date is in UTC format

  • Then run the script in PowerShell console
  • After the script finishes its job, you can see the result it's have Azure Virtual Machine infomation.


Function Set-AzureVirtualMachineExpiredDate 

    # get vm info 
    $targetVMInfo = Get-AzureRmResource | Where { $_.Name -eq "$LabName/$VMName" -and $_.ResourceType -eq 'Microsoft.DevTestLab/labs/virtualMachines' } 

    # if not find, throw exception 
    If ($targetVMInfo -eq $null) { 
        Throw "No VM naming $VMName" 

    # get vm properties 
    $vmInfoWithProperties = Get-AzureRmResource -ResourceId $targetVMInfo.ResourceId -ExpandProperties 
    $vmProperties = $vmInfoWithProperties.Properties 

    # set expired date 
    $vmProperties | Add-Member -MemberType NoteProperty -Name expirationDate -Value $ExpiredUTCDate 
    Set-AzureRmResource -ResourceId $targetVMInfo.ResourceId -Properties $vmProperties -Force 

    Write-Host "Successfully to set VM "$LabName/$VMName" to expire on UTC $ExpiredUTCDate" 

# 1. login azure 

# 2. fill target vm name, lab name and expired date 
Set-AzureVirtualMachineExpiredDate -VMName "lab-autoexpired" -LabName "eric-lab" -ExpiredUTCDate "2016-10-10" 

Additional Resources