Auto shutdown an Azure VM with PowerShell

At one of my costumers, after starting the process of Azure Governance, it come to my attention the following scenario, the majority of the Virtual Machines on the DevTest Labs were with no auto shutdown configuration.

That can be setup easily, although we want to make sure that we wanted to introduce a mechanism that will enforce the shutdown of those virtual machine, even if that configuration is not setup. One of the ways to make sure, is to correct the deployment of those workloads from the Azure DevOps side, by enforcing the auto shutdown field to be mandatory.

On the other hand, we wanted to make sure, if anyone used an old template or using the portal, we could reduce the cost of running those workloads, by implementing an enforce mechanism to shutdown the workloads without any auto shutdown configuration.

The solution that we create was based on an Azure automation. We create a runbook that validate if the workload has the auto shutdown configuration, if not, Azure Automation will shutdown that workload. A very simple runbook, although very effective to reduce the cost and implement an overall auto shutdown policy to those kinds of workloads.

This is the script that we used:

$RunningVMs = Get-AzureRmVM -Status | Where-Object {$_.PowerState -eq “VM running” -and $_.Tags[“ShutdownPolicy”] -ne “Excluded”}

$DevTestLabs = Get-AzureRmResource | Where-Object {$_.ResourceType -eq “Microsoft.DevTestLab/schedules”}

$RunningVMs | ForEach-Object -Process {

    $ShutDownName = “shutdown-computevm-{0}” -f $_.Name

    if ($DevTestLabs.Name -notcontains $ShutdownName) {

        Write-Output “Will shutdown VM $($_.Name)”

        $_ | Stop-AzureRmVM -Force -Confirm:$false 




Marcos Nogueira
Azure MVP
Twitter: @mdnoga

Marcos Nogueira

With more than 18 years experience in Datacenter Architectures, Marcos Nogueira is currently working as a Principal Cloud Solution Architect. He is an expert in Private and Hybrid Cloud, with a focus on Microsoft Azure, Virtualization and System Center. He has worked in several industries, including Aerospace, Transportation, Energy, Manufacturing, Financial Services, Government, Health Care, Telecoms, IT Services, and Gas & Oil in different countries and continents. Marcos was a Canadian MVP in System Center Cloud & Datacenter Managenment and he has +14 years as Microsoft Certified, with more than 100+ certifications (MCT, MCSE, and MCITP, among others). Marcos is also certified in VMware, CompTIA and ITIL v3. He assisted Microsoft in the development of workshops and special events on Private & Hybrid Cloud, Azure, System Center, Windows Server, Hyper-V and as a speaker at several Microsoft TechEd/Ignite and communities events around the world.

Leave a Reply

Your email address will not be published. Required fields are marked *