David Rigdon

Systems Administrator

Azure VDI Shut Down Unused Session Hosts | David Rigdon

Azure VDI Shut Down Unused Session Hosts

February 18, 2025

Save Major Moolah on Cloud Spend

Image References the Ted and Robin military salute from How I Met Your Mother

I noticed that we had a couple Azure Virtual Desktop environments that were running 24/7, however users would only connect to the machines for an 8-10 hour period, which meant those machines were sitting there unused for a large portion of the day, thus costing significant money over the course of the month.

I began looking into how we could remedy that situation, and discovered a nifty way to query the virtual machines themselves to see if there are any logged on users, and if not, power down the VM thus stopping billing. These Azure machines were in a host pool of 8 machines using the size “E4ads v5” which at the time cost $0.4460 hourly, so if we shut them down we saved roughly $7 a day per machine, totaling ~$1500/month in cloud spend savings. You’d still get billed for the cost of storage and networking, but a deallocated VM costs pennies on the dollar compared to a running VM that isn’t being used…


Step 1: Create an Azure Function App

This Azure Function app utilizes the Powershell code linked at the bottom of this post to scan any defined VDI session hosts, check if there are any logged on users, and if not power down and deallocate (stop) the VM.


Step 1a: Manual definitions of module versions

Notably, due to the constant updating of AZ modules and dependencies, I had to manually define the AZ modules in the requirements.psd1 in the Azure Function App file


Step 2: System Managed Identity

Add a system managed identity in Entra Give the below rights to said system managed identity:


Step 3: Configure start on connect.

  1. You’ll first need to add the “Desktop Virtualization Power On Contributor” RBAC role to the “Azure Virtual Desktop” service principal at the subscription level. It cannot be narrowed down to the resource group, as this prevents it from working properly.
  2. In the Azure Portal under the “Azure Virtual Desktop” app, you would enable “Start VM on connect” in the Host Pool properties. Resource on Microsoft Learn

Step 4: Configure GPO

  1. Set GPOs to log out disconnected sessions after a time limit, else the sessions will stay active and will never shut down.

Credits:

I based my work off the work below by Travis Roberts: