Forum Discussion

Ashish_Arya's avatar
Ashish_Arya
Brass Contributor
Dec 19, 2023

How to reduce the script execution time to shut down the unused Hostpool AVDs

Hi Team,
 
Below is the attached script which I am using to shut down the unsed AVDs (which are not in deallocated state) to save some cost.
The issue with this script is that it is taking lot of time for its execution.
 
I think the only issue is because Get-AzWvdSessionHost cmdlet from the Az.DesktopVirtualization PowerShell module does not have any property related to PowerState of the VM. This is why I am forced to use the Get-AzVm cmdlet from the Az PowerShell module to get each AVDs power state and this is what I think could be the reason of its slowness. 
 
I am unable to fix the script and need help to optimize this script.

# Displaying the script execution start time
$ScriptStartTime = Get-Date -Format "dd-MM-yyyy hh:mm:ss"
Write-Output "`n##########################################"
Write-Output "Script start time: $ScriptStartTime"
Write-Output "##########################################`n"

# Defining the array of hostpool objects
$allHostPools = @(
    [pscustomobject]@{
        HostPool   = "HostPool Name"
        HostPoolRG = "Hostpool resource group name"
    }
)

# Looping through all the hostpools
For ($i = 0; $i -lt $allHostPools.Length; $i++) {

    $pool = $allHostPools[$i].HostPool
    $poolrg = $allHostPools[$i].HostPoolRG

    Write-Output "##################################################"
    Write-Output "HostPool Name           : $pool"
    Write-output "HostPool Resource group : $poolRg"
    Write-Output "##################################################`n"

    # Get the Session Hosts which are in Drain Mode off and does not have any active session
    try {
        $runningSessionHosts = Get-AzWvdSessionHost -ErrorAction 'Stop' -HostPoolName $Pool -ResourceGroupName $PoolRg | `
                                Where-Object {($_.AllowNewSession -eq $true) -and ($_.Session -eq 0) } | `
                                Sort-Object { [int]($_.Name.Split("/")[1] -replace '.*-(\d+)', '$1')}
    }
    catch {
        $ErrorMessage = $_.Exception.message
        Write-Error ("Error getting a list of running session hosts: " + $ErrorMessage)
        Break
    }

    #Evaluate the list of running session hosts to shutdown the VM which are not in the deallocated state
    $Count = 0
    Foreach ($sessionHost in $runningSessionHosts) {
        $Count = $Count + 1
        $sessionHostName = ($sessionHost).name.split('/')[1]
        $VM = Get-Azvm -Name $sessionHostName -Status -ErrorAction Stop
        if ($VM.PowerState -ne "VM deallocated") {
            Write-Output "$Count. The session host $sessionHostName does not have an active session and also in running state."
            Try {
                # Stop the VM
                Write-Output "    Hence, stopping the $sessionHostName session host..."
                $VM | Stop-AzVM -ErrorAction 'Stop' -Force -NoWait | Out-Null
                Write-Output "    The $sessionHostName session host was stopped successfully.`n"
            }
            Catch {
                $ErrorMessage = $_.Exception.message
                Write-Error ("Error stopping the VM: " + $ErrorMessage)
                Break
            }
        }
        else {
            write-Output "$Count. The session host $sessionHostName is already in shut down state.`n"
        }
    }
}

# Displaying the script end time
$ScriptEndTime = Get-Date -Format "dd-MM-yyyy hh:mm:ss"
Write-Output "`n= = = = = = = = = = = = = = = = = = = = ="
Write-Output "Script end time : $ScriptEndTime"
Write-Output "= = = = = = = = = = = = = = = = = = = = =`n"

1 Reply

  • NKC25's avatar
    NKC25
    Brass Contributor

    Ashish_Arya 

     

    Not sure if this can help you, test out in non prod 🙂 first use this module Az.AVD (https://www.powershellgallery.com/packages/Az.Avd/3.1.1) you have options to get the powerstate of the virtual machine, though inside the module it will use the restapi  instanceview of the VM, but it might be faster compare to get-azvm. 

    https://www.powershellgallery.com/packages/Az.Avd/3.1.1/Content/Public%5CGet-AvdSessionHostPowerState.ps1

     

     

Resources