Decommissioning Azure Virtual desktop Hostpool

Decommissioning Azure Virtual desktop Hostpool

Using PowerShell + Az Module to delete Azure Virtual Desktop resources

There are a lot of tutorials on how to setup an AVD Hostpool in Azure but very few on how to properly decommission it. Just simply deleting all the session hosts is a half story. There are VMs, disks, Network Interfaces, Application Groups that need to be deleted as well to save cost.

In this article, I will share a simple PowerShell Script on how to efficiently achieve this using Azure CLI module with less manual efforts.

Copy the PowerShell script below and make sure to change the variable values on the top. Also, keep in mind this script is best suited if all the resources belonging to a Hostpool exist in the same Resource Group. If any additional resources exist in the same Resource Group, make sure to filter them out in your script to avoid deletion.

Connect-AzAccount

#Set the scope and Resource group
Set-AzContext "SUBSCRIPTION-NAME"
$rg = "RESOURCE-GROUP-NAME"
$hp = "HOSTPOOL-NAME"

#MAKE SURE THERE ARE NO OTHER VMs, Disks, NICs in the same Resource group other than the ones that you need to delete
#You can filter it using -Name VM-Name* property
$AVDs = Get-AzWvdSessionhost -ResourceGroup $rg -HostPoolName $hp
$disks = Get-AzDisk -ResourceGroup $rg | Select-Object Name
$VMs = Get-AzVM -ResourceGroup $rg | Select-Object Name
$NICs = Get-AzNetworkInterface -ResourceGroup $rg | Select-Object Name

#Remove Session Host
foreach ($AVD in $AVDs){
    Remove-AzWvdSessionHost -HostPoolName $hp -Name $AVD.Name -ResourceGroupName $rg -Force
    Write-Host "Removed $AVD"
}

#Delete VMs
foreach ($VM in $VMs){
    Remove-AzVM -ResourceGroupName $rg -name $VM.Name -Force
    Write-Host "Deleted $VM"
}

#Delete Disks associated with the VMs
foreach ($disk in $disks){
    Remove-AzDisk -ResourceGroupName $rg -name $disk.Name -Force
    Write-Host "Deleted $disk"
}

#Delete Network Interfaces associated with VMs
foreach ($NIC in $NICs){
    Remove-AzNetworkInterface -ResourceGroupName $rg -name $NIC.Name -Force
    Write-Host "Deleted $NIC"
}