Thursday, June 2, 2022

Kill a User's Citrix Desktop or Application Session

 A user asked for an easy way via PowerShell to kill a user's Citrix application or desktop session.

On one of the Delivery Controllers, save the below script as Logoff-Sessions.ps1, and execute it. 

You will be prompted for the username (entered as domain\username), and then all of the user's sessions will be listed.

You will be asked for confirmation when you make your selection before logging the session off.

Function Logoff-Session {

    # logoff a specified user's session

    asnp Citrix*

    $user = Read-Host -Prompt "Enter User Name (domain\user format)"
    if ($user -ne '') {
        $sessions = @(Get-BrokerSession | ? username -eq $user |
            Select  @{n='SessionKey'; e={$_.SessionKey}},
                    @{n='Host/Desktop'; e={$_.MachineName}},
                    @{n='Application(s)'; e={$_.ApplicationsInUse}})

        if ($sessions.count -eq 0) {
            Write-Host "Sorry ... there are no applications active for $($user)."
        } else {
            Write-Host 'Session#'.Padright(10) 'Host/Desktop'.PadRight(30) 'Application(s)'
            for ($i=0; $i -lt $sessions.Count; ++$i) {
                $sessnum = $i + 1
                Write-Host $sessnum.ToString().PadLeft(5) '    ' $sessions[$i].'Host/Desktop'.PadRight(30) $sessions[$i].'Application(s)'
            $logoff = Read-Host "Which session would you like to log off (0 to exit)?"

            if ($logoff -eq 0 -or $logoff -eq '') {
            if ($logoff -le $sessions.Count) {
                $sessnum = $logoff - 1
                Write-Host $sessions[$sessnum].'Host/Desktop'.PadRight(30) $sessions[$sessnum].'Application(s)'
                $yn = Read-Host "Is this the session you would like to logoff (Y/N)?"
                if ($yn -eq 'Y') {
                    Stop-BrokerSession $sessions[$sessnum].SessionKey