This script can be used to log off a user from Azure Virtual Desktops or you can integrate this with a request form and use it for user self-service.
#Gets all Resource Groups to check for Host Pools
#Specify UPN for the user you want to log off.
$UPN = Kyle.Wise@
$resourceGroups = Get-AzResourceGroup
foreach ($resourceGroup in $resourceGroups) {
$hostPools = Get-AzWvdHostPool -ResourceGroupName $resourceGroup.ResourceGroupName
Write-Output "Checking $($hostPools.Count) host pools in resource group
$($resourceGroup.ResourceGroupName)"
# Loop through each host pool in the resource group for "Pooled Type"
foreach ($hostPool in $hostPools) {
# Check if the hostpool is Pooled
if($hostPool.HostPoolType -eq 'Pooled'){
Write-Output "Checking host pool $($hostPool.Name) in resource group
$($resourceGroup.ResourceGroupName)"
# Get the user sessions for the host pool
$userSessions = Get-AzWvdUserSession -ResourceGroupName
$resourceGroup.ResourceGroupName -HostPoolName $hostPool.Name | Select-Object
"ActiveDirectoryUserName","ApplicationType","CreateTime","Id","Name","ObjectId","SessionState","Type","UserPrincipalName"
# Search for the user principal name
$upnSession = $userSessions | Where-Object { $_.UserPrincipalName -eq $upn }
if ($upnSession) {
$SessHost = ($upnSession.Name -split "/")[-2]
$CurSessID = ($upnSession.Id -split "/")[-1]
Write-Output "Removing user session with ID $CurSessID and UPN $upn on
session host $SessHost in host pool $($hostPool.Name) in resource group
$($resourceGroup.ResourceGroupName)"
try{
if($upnSession.SessionState -eq "Active" -or $upnSession.SessionState -eq
"Disconnected"){
Remove-AzWvdUserSession -ResourceGroupName $resourceGroup.ResourceGroupName
-HostPoolName $hostPool.Name -SessionHostName $SessHost -Id $CurSessID
}
}
catch{
Write-Output "$_"
}
} else {
Write-Output "No user session found for UPN $upn in host pool
$($hostPool.Name) in resource group $($resourceGroup.ResourceGroupName)"
}
}
}
}