Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
drain-xaserver.ps1 gist 3
while ($sessCount -ge 0) {
$xaSessions = (Get-XASession -ComputerName $XMLBroker -ServerName $XenAppServerName -full | where {($_.State -eq 'Active' -or $_.State -eq 'Disconnected') -and $_.Protocol -eq 'Ica'} | select SessionId,accountname,state,lastinputtime -Unique)
$sessCount = ($xaSessions | measure).count
$curTime = (get-date -Format T)
write-host "Current time is: $curTime"
Write-Host "Current session Count = $sessCount on $XenAppServerName" -ForegroundColor White
if ($sessCount -eq 0) {
Write-Host "$XenAppServerName is free of users (ICA Sessions)" -ForegroundColor White
Exit 0
} else {
$disconnected = @()
Write-Host "Checking for disconnected and idle users on $XenAppServername" -ForegroundColor White
$disconnected = $xaSessions | Where-Object {$_.State -eq 'Disconnected'}
$active = $xaSessions | Where-Object {$_.State -eq 'Active'}
if ($timeout -ne 0) { # Check if aggression is not Green, otherwise don't look at Active sessions
foreach ($idleuser in $active) {
$idleusertime = (New-TimeSpan -Start (get-date) -End $idleuser.LastInputTime).negate().Minutes + ((New-TimeSpan -Start (get-date) -End $idleuser.LastInputTime).negate().hours * 60)
if ($idleusertime -gt $timeOut) {
$user = $idleuser.accountname.Tostring()
write-verbose "$user has been idle for $idleusertime minutes. They will be disconnected."
[array]$disconnected += $idleuser
}
}
$xaSessions = (Get-XASession -ComputerName $XMLBroker -ServerName $XenAppServerName -full | where {($_.State -eq 'Active' -or $_.State -eq 'Disconnected') -and $_.Protocol -eq 'Ica'} | select SessionId,accountname,state,lastinputtime -Unique)
$sessCount = ($xaSessions | measure).count
}
if ($disconnected -eq $null) {
Write-Host "There are no disconnected sessions on $XenAppServerName" -ForegroundColor White
Write-Host "Waiting 10 minutes" -ForegroundColor Red
Start-Sleep -Seconds 600
} else {
Write-host "Logging off" ($disconnected | measure).count "disconnected users from $XenAppServerName" -ForegroundColor White
foreach ($user in $disconnected) {
$namedUser = $user.AccountName
write-host "Logging off $namedUser" -ForegroundColor White
Stop-XASession -ComputerName $XMLBroker -ServerName $XenAppServerName -SessionId $user.SessionId
}
$xaSessions = (Get-XASession -ComputerName $XMLBroker -ServerName $XenAppServerName -full | where {($_.State -eq 'Active' -or $_.State -eq 'Disconnected') -and $_.Protocol -eq 'Ica'} | select SessionId,accountname,state,lastinputtime -Unique)
$sessCount = ($xaSessions | measure).count
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment