Script to Restart an AVD Session Host When Unavailable (Safely)
By Jay H.Published Updated 10 min read
Jay H. · Founder, Sessionright
Founder of Sessionright. Twenty years running Citrix, NetScaler, Citrix Cloud, NetScaler Console, Azure and Azure Virtual Desktop estates; writes the guides and reviews the platform's rules.
Stuck on this right now? Talk it through with a Sessionright engineer: 15 minutes, free.
An Azure Virtual Desktop session host in Unavailable is either turned off or has failed a fatal health check, and the broker sends it no new sessions (session host statuses). For one of those failures, the side-by-side stack listener, Microsoft's own first step is "Try restarting your virtual machine (VM)". That makes a scheduled restart script tempting. Written carelessly, it signs users out, restarts hosts that a reboot cannot fix, and wipes the evidence you needed.
This guide gives you a PowerShell script that is read-only unless you pass -Execute. It finds Unavailable hosts, skips the ones a restart will not help, drains each candidate, waits for zero sessions, restarts it, re-checks the status and logs every step. It also covers the roles a managed identity needs to run it on a schedule, and what to leave to a human.
When a restart is the right fix, and when it hides the cause
Map the status, and the failed health check behind it, to an action before you script anything. The statuses and checks below come from Microsoft's health check reference and the Session Hosts REST API, which notes that Unavailable "replaces previous 'NoHeartBeat' status".
| Status or failed check | What it means | Restart? |
|---|---|---|
Unavailable, VM not running |
Host is turned off | No. Start the VM |
Shutdown |
Agent reported the VM stopped or deallocated | No. Start the VM |
Unavailable, SxSStackListenerCheck failed |
Stack not listening; fatal | Yes, Microsoft's first step |
Unavailable, DomainJoinedCheck failed |
Not joined to a domain; fatal | No. Fix the join |
Unavailable, DomainTrustCheck failed |
Trust relationship lost; fatal | No. Repair the secure channel |
Needs Assistance |
Non-fatal check failed (Geneva, IMDS, URLs); users still connect | No. A restart would sign users out |
Upgrade Failed |
Agent couldn't update; doesn't affect sessions | No. Follow agent troubleshooting |
Two traps sit in this table. First, a host that shuts down before its agent reports the change shows Unavailable, not Shutdown, so Microsoft says to use the VM instance view to read the real power state. The script does that with Get-AzVM -Status. Second, a restart that "works" can hide a cause that comes back. For example, a DisableRegistryTools policy stops the agent installing the side-by-side stack and leaves hosts stuck in Unavailable (agent troubleshooting). No number of restarts fixes that. That is why the script logs the failed checks before it acts: the log is your evidence that the same host keeps coming back. Our session host unavailable guide covers the fixes for each check, and the AVD health check checklist covers the wider review.
Find the hosts read-only first
Run this before you write any automation. Get-AzWvdSessionHost lists every host in the pool (Get-AzWvdSessionHost). The returned object exposes Status, Session (the number of sessions), AllowNewSession, LastHeartBeat and ResourceId, the resource ID of the underlying VM (SessionHost model).
$pool = @{ ResourceGroupName = '<ResourceGroupName>'; HostPoolName = '<HostPoolName>' }
Get-AzWvdSessionHost @pool |
Select-Object Name, Status, Session, AllowNewSession, LastHeartBeat, ResourceId |
Format-Table -AutoSize
For each Unavailable host, read the failed checks and the VM power state. Health check results are Unknown, HealthCheckSucceeded, HealthCheckFailed or SessionHostShutdown (REST reference). Get-AzVM -ResourceId <id> -Status returns the instance view, where a running VM shows PowerState/running (Get-AzVM).
$h = Get-AzWvdSessionHost @pool -Name '<SessionHostName>'
$h.HealthCheckResult | Where-Object HealthCheckResult -eq 'HealthCheckFailed' |
Select-Object HealthCheckName, AdditionalFailureDetailMessage
(Get-AzVM -ResourceId $h.ResourceId -Status).Statuses | Where-Object Code -like 'PowerState/*'
Get-AzWvdUserSession @pool -SessionHostName '<SessionHostName>' | Select-Object Name, SessionState, UserPrincipalName
The Name that Get-AzWvdSessionHost returns is HostPoolName/SessionHostName, as the cmdlet's examples show. Use only the part after the slash for -Name and -SessionHostName.
Drain, wait for zero sessions, restart, re-check
The sequence follows Microsoft's drain mode guidance: a drained host accepts no new sessions, and existing connections "remain active until the user signs out or an administrator ends the session". Only then do you do the maintenance.
- Drain.
Update-AzWvdSessionHost @pool -Name <host> -AllowNewSession:$false(Update-AzWvdSessionHost). Wait at least 60 seconds before you trust the portal view. - Wait for zero sessions. Poll
Get-AzWvdUserSession @pool -SessionHostName <host>(Get-AzWvdUserSession) until it returns nothing, up to a timeout. If sessions remain, stop and leave the host drained for a person to look at. - Restart.
Restart-AzVM -Id <ResourceId>. Without-NoWaitthe cmdlet waits for the operation to complete (Restart-AzVM). - Re-check. Poll
Get-AzWvdSessionHostuntilStatusisAvailableor a timeout passes. Remove the drain only if the host is Available and was accepting sessions before you started.
The script
Save as Restart-UnavailableAvdHost.ps1. It needs the Az.Accounts, Az.Compute and Az.DesktopVirtualization modules.
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)] [string] $ResourceGroupName,
[Parameter(Mandatory)] [string] $HostPoolName,
[ValidateRange(1, 3)] [int] $MaxHostsPerRun = 1,
[ValidateRange(1, 120)] [int] $DrainWaitMinutes = 15,
[ValidateRange(5, 60)] [int] $RecheckMinutes = 15,
[switch] $Execute,
[switch] $UseManagedIdentity,
[string] $LogPath = (Join-Path ([IO.Path]::GetTempPath()) "avd-restart-$(Get-Date -Format yyyyMMdd-HHmmss).log")
)
$ErrorActionPreference = 'Stop'
function Write-Log([string] $Message) {
$line = '{0:u} {1}' -f (Get-Date).ToUniversalTime(), $Message
Write-Host $line
Add-Content -Path $LogPath -Value $line -WhatIf:$false
}
if ($UseManagedIdentity) {
Disable-AzContextAutosave -Scope Process | Out-Null
Connect-AzAccount -Identity | Out-Null
}
if (-not $Execute) { $WhatIfPreference = $true } # dry run: ShouldProcess returns $false
$pool = @{ ResourceGroupName = $ResourceGroupName; HostPoolName = $HostPoolName }
$noRestartFix = 'DomainJoinedCheck', 'DomainTrustCheck'
$candidates = foreach ($h in Get-AzWvdSessionHost @pool) {
$name = ($h.Name -split '/')[-1]
$failed = @($h.HealthCheckResult | Where-Object HealthCheckResult -eq 'HealthCheckFailed').HealthCheckName
Write-Log "$name status=$($h.Status) sessions=$($h.Session) allowNew=$($h.AllowNewSession) failed=[$($failed -join ',')]"
if ($h.Status -ne 'Unavailable') { continue }
$power = ((Get-AzVM -ResourceId $h.ResourceId -Status).Statuses | Where-Object Code -like 'PowerState/*').Code
if ($power -ne 'PowerState/running') { Write-Log "$name SKIP: $power, start the VM instead"; continue }
if ($failed | Where-Object { $_ -in $noRestartFix }) { Write-Log "$name SKIP: domain check failed, a restart will not fix it"; continue }
[pscustomobject]@{ Name = $name; ResourceId = $h.ResourceId; AllowNewSession = $h.AllowNewSession }
}
$selected = @($candidates | Select-Object -First $MaxHostsPerRun)
Write-Log "candidates=$(@($candidates).Count) selected=$($selected.Count) execute=$Execute"
foreach ($c in $selected) {
if (-not $PSCmdlet.ShouldProcess($c.Name, 'Drain, wait for zero sessions, restart, re-check')) { continue }
Update-AzWvdSessionHost @pool -Name $c.Name -AllowNewSession:$false | Out-Null
Write-Log "$($c.Name) drained"
$deadline = (Get-Date).AddMinutes($DrainWaitMinutes)
do {
$sessions = @(Get-AzWvdUserSession @pool -SessionHostName $c.Name).Count
if ($sessions -eq 0) { break }
Write-Log "$($c.Name) waiting: $sessions session(s)"
Start-Sleep -Seconds 60
} while ((Get-Date) -lt $deadline)
if ($sessions -gt 0) {
Write-Log "$($c.Name) SKIP: $sessions session(s) after $DrainWaitMinutes min, left drained for a human"
continue
}
Restart-AzVM -Id $c.ResourceId | Out-Null
Write-Log "$($c.Name) restart completed"
$deadline = (Get-Date).AddMinutes($RecheckMinutes)
do {
Start-Sleep -Seconds 60
$status = (Get-AzWvdSessionHost @pool -Name $c.Name).Status
} while ($status -ne 'Available' -and (Get-Date) -lt $deadline)
if ($status -eq 'Available' -and $c.AllowNewSession) {
Update-AzWvdSessionHost @pool -Name $c.Name -AllowNewSession:$true | Out-Null
Write-Log "$($c.Name) Available, drain removed"
} else {
Write-Log "$($c.Name) status=$status after restart, left drained: investigate"
}
}
Run it read-only first and read the log:
.\Restart-UnavailableAvdHost.ps1 -ResourceGroupName rg-avd -HostPoolName hp-pooled-01
Every candidate prints a What if: line and nothing changes. Add -Execute only after the dry run selects the host you expect.
The guardrails
- Never restart a host with sessions. The script restarts only after
Get-AzWvdUserSessionreturns zero, checked after the drain. It never signs anyone out. If sessions stay past-DrainWaitMinutes, it leaves the host drained and logs it. - Cap hosts per run.
-MaxHostsPerRundefaults to 1 andValidateRangerefuses anything above 3. If half a pool is Unavailable at once, the cause is shared (DNS, a domain controller, a blocked endpoint, a bad update), and restarting everything removes capacity while hiding it. Microsoft's autoscale scenarios show users getting a "No resources available" error when no session host can be turned on for them (autoscale scenarios). See our no available resources guide. -WhatIfby default.[CmdletBinding(SupportsShouldProcess)]adds-WhatIfand-Confirmto the script (CmdletBinding attribute). Setting$WhatIfPreferenceto$trueturns WhatIf on "on any command that supports it" (preference variables). That includesUpdate-AzWvdSessionHostandRestart-AzVM, which both list-WhatIfin their syntax. The log write passes-WhatIf:$falseso a dry run still leaves a record.- Log every action. Each host gets a line with its status, session count, drain state and failed checks before anything happens, then one line per action. In Automation, ship the log to storage you keep, because a log you can't find later is no audit trail.
- Respect the prior drain state. If a person had already drained the host, the script never re-enables it.
- Exclude from autoscale. For pooled pools, autoscale overwrites drain mode. A VM carrying the scaling plan's exclusion tag is not turned on, off or changed in drain mode by autoscale (autoscale scenarios). Microsoft's example tag name is
excludeFromScaling(create a scaling plan). Tag the target before an-Executerun and remove the tag afterwards.
Running it on a schedule with a managed identity
- Enable the identity. Turn on the system-assigned managed identity on an Azure Automation account (managed identity for Automation). The
-UseManagedIdentityswitch runsDisable-AzContextAutosave -Scope ProcessandConnect-AzAccount -Identity, the pattern Microsoft documents on the same page. - Assign the roles. Microsoft's guidance is to assign "only required" permissions to the runbook identity. The script needs three things:
- Read session hosts and user sessions, and change drain mode. Desktop Virtualization Session Host Operator allows "viewing and removing session hosts, and changing drain mode", and its actions include
Microsoft.DesktopVirtualization/hostpools/sessionhosts/*(AVD built-in roles). Assign it on the host pool. - Read the VM, its instance view, and restart it. No AVD role is scoped to just that. Create a custom role with
Microsoft.Compute/virtualMachines/read,Microsoft.Compute/virtualMachines/instanceView/readandMicrosoft.Compute/virtualMachines/restart/action, and assign it on the session hosts' resource group. - Avoid the shortcuts. Virtual Machine Contributor grants
Microsoft.Compute/virtualMachines/*, which includes running scripts on VMs (compute built-in roles). Desktop Virtualization Power On Off Contributor does includerestart/action, but Microsoft describes it as the role for the Azure Virtual Desktop resource provider, and it also carriesusersessions/delete.
- Read session hosts and user sessions, and change drain mode. Desktop Virtualization Session Host Operator allows "viewing and removing session hosts, and changing drain mode", and its actions include
- Assign with PowerShell. Use
New-AzRoleAssignment -ObjectId <identity-object-id> -Scope <scope> -RoleDefinitionName '<role>', as in Microsoft's example. - Schedule. Link the runbook to a recurring schedule. The most frequent interval is one hour; for every 15 minutes, Microsoft suggests four hourly schedules offset by 15 minutes (Automation schedules). Pass
-Executein the schedule's parameters only after a week of dry runs has selected the hosts you would have picked by hand.
What not to automate
- Signing users out. Don't let an unattended script call logoff or session removal to get to zero. A host that keeps sessions is a human decision.
- Restarting Needs Assistance hosts. Users can still connect to them, and the failed checks (URLs, IMDS, Geneva) point at network or agent fixes a reboot won't make.
- Starting VMs that are off. That is a capacity decision for your scaling plan, not a repair. An unexpected Shutdown deserves a look at who or what stopped the VM.
- Agent reinstall and re-registration. These need a new registration key and steps on the VM (agent troubleshooting). Keep them as a reviewed runbook a person starts.
- Repeat restarts. If the log shows the same host restarted on consecutive runs, stop. Remove it from scope and find the cause.
FAQ
How do I restart an AVD session host with PowerShell?
Drain it with Update-AzWvdSessionHost -AllowNewSession:$false, confirm Get-AzWvdUserSession returns no sessions, then run Restart-AzVM -ResourceGroupName <rg> -Name <vm> or Restart-AzVM -Id <ResourceId>. Re-check Status before you remove the drain.
Why is my AVD session host still Unavailable after a restart?
The cause is usually one a reboot doesn't touch: a failed domain join or trust check, an expired registration, or a broken side-by-side stack install. Read HealthCheckResult and the agent events in our session host unavailable guide.
Can a session host show Unavailable when the VM is just shut down?
Yes. If the VM shuts down before the agent reports it, the portal shows Unavailable instead of Shutdown. Read PowerState from Get-AzVM -Status before you act.
What permissions does a runbook need to restart session hosts?
Desktop Virtualization Session Host Operator on the host pool for drain mode and session reads, plus VM read, instance view read and restart on the VMs. A custom role is the narrowest way to grant the VM actions.
How often can an Azure Automation runbook run on a schedule?
Once an hour per schedule. For a 15-minute cadence, Microsoft suggests four hourly schedules that start 15 minutes apart.
Want a second pair of eyes?
Before you schedule any restart, it helps to know which hosts fail which checks and how often. Sessionright's free assessment is one read-only command in Azure Cloud Shell that produces an HTML report in about five minutes. If you later want changes like this drain-and-restart to run as a plan you review, Sessionright for Azure Virtual Desktop is read-only by default, and every change is approved and logged (how we handle security). If you would rather talk it through, book a 15-minute call: no install, no sales deck.
Sources
- Microsoft Learn: Session host statuses and health checks in Azure Virtual Desktop
- Microsoft Learn: Session Hosts - Get (REST API, 2026-04-16)
- Microsoft Learn: Troubleshoot common Azure Virtual Desktop Agent issues
- Microsoft Learn: Get-AzWvdSessionHost
- Microsoft Learn: Update-AzWvdSessionHost
- Microsoft Learn: Get-AzWvdUserSession
- Microsoft Learn: SessionHost class (Az.DesktopVirtualization models)
- Microsoft Learn: Restart-AzVM
- Microsoft Learn: Get-AzVM
- Microsoft Learn: Drain session hosts for maintenance in Azure Virtual Desktop
- Microsoft Learn: Autoscale scaling plans and example scenarios
- Microsoft Learn: Create and assign an autoscale scaling plan
- Microsoft Learn: Built-in Azure RBAC roles for Azure Virtual Desktop
- Microsoft Learn: Azure built-in roles for Compute
- Microsoft Learn: Azure custom roles
- Microsoft Learn: Using a system-assigned managed identity for an Azure Automation account
- Microsoft Learn: Manage schedules in Azure Automation
- Microsoft Learn: about_Functions_CmdletBindingAttribute
- Microsoft Learn: about_Preference_Variables
Want this watched for you, with the fix drafted before you ask?
Sessionright is an AI operator for Azure Virtual Desktop: it checks session hosts, scaling plans, FSLogix and cost continuously, attaches the evidence, and proposes fixes for a named approver to sign. It has run against simulated estates and Sessionright's own Azure lab tenant so far. To see what it finds on your own estate, run the free assessment: one command in Azure Cloud Shell reads your estate, never changes it, and writes an HTML report in about five minutes for a typical estate. Your estate data stays with you unless you choose to email yourself the HTML report through Sessionright. Design partner program: 90-day free Operator pilot, then 50% off year 1; list price at signing held to month 24. Engineer-led assessments are 50% off for design partners. Outside the program the onboarding assessment is $2,500, up to 500 users, one tenant.
Not ready for that? Talk to a Sessionright engineer: 15 minutes, free, and you leave with a next step.
Or get the next guide by email. One email per new guide, no marketing list.
Related guides
- AVD Session Host Unavailable or Needs Assistance: How to Fix
Fix an AVD session host stuck in Unavailable, Needs Assistance or Upgrade Failed: read the health checks, re-register the agent and test required URLs.
- Citrix® Health Check PowerShell Script (Free, Read-Only)
A free, read-only Citrix health check PowerShell script for CVAD and DaaS: 15 checks built on documented SDK cmdlets, written to one colour-coded HTML report.
- Citrix Health Check Checklist: 45 Checks for CVAD and DaaS
A 45-point Citrix health check for CVAD, DaaS and NetScaler® Gateway: the cmdlet, console path or CLI command for each check, and what good looks like.
- AVD Autoscale Limitations: Where Native Scaling Plans Stop
The limits Microsoft documents for native AVD autoscale, how power management and dynamic autoscaling differ, and which jobs need another native feature.
- AVD Health Check: 40-Point Checklist for Azure Virtual Desktop
A 40-point AVD health check for Azure Virtual Desktop: the PowerShell, portal path or query for each check, what good looks like, and the Microsoft source.
Citrix and NetScaler are trademarks of Citrix Systems, Inc. and/or its affiliates. Azure is a trademark of the Microsoft group of companies. Sessionright is not affiliated with or endorsed by Cloud Software Group, Citrix or Microsoft.