Jump to content
Welcome to our new Citrix community!
  • 0

PowerShell script that detects disconnected sessions


Andrew Kaplan

Question

Hello --

I am using Director to monitor sessions on our server, and if I observe a session in a Disconnected state for an 'extended' period of time, I proceed to log off the user. I am looking into setting up e-mail notifications so that I will be notified of such events.

I am planning on using PowerShell to send the e-mail notifications. What I also need to do is have PowerShell periodically check for disconnected sessions. Does anyone know what command syntax I would be able to use in order to accomplish this task?

Thanks.

Link to comment

18 answers to this question

Recommended Posts

  • 1

You need to load the XenDesktop SDK snap-ins into the PowerShell shell instance, with the 'Add-PsSnapin' cmdlet.

If you just want the broker service cmdlets, you can say:

Add-PsSnapin Citrix.Broker.Admin.V2

or you can add all of the installed Citrix snapins with

Add-PsSnapin Citrix.*

You can also get a shell instance with the right snapins loaded through the 'Launch PowerShell' button on the bottom of the 'PowerShell' tab of the Studio console root node.

Regards
William

  • Like 1
Link to comment
  • 0

The 'Get-BrokerSession' cmdlet can be directly used to get a list of the sessions that have been disconnected for at least some target length of time. The result of this can then be used in a PowerShell script to then email to somewhere, or event to automatically log these session off of that is the desired action. The cmdlet parameters to (for example) find disconnected sessions that have been disconnected for 4 hours or more would be:

Get-BrokerSession -SessionState Disconnected -Filter { SessionStateChangeTime -lt "-4:00" }

The edocs help for the cmdlet is at:
http://support.citrix.com/proddocs/topic/citrix-broker-admin-v2-xd7/get-brokersession-xd7.html

and the help for the filter syntax (including time ranges) is at:
http://support.citrix.com/proddocs/topic/citrix-broker-admin-v2-xd7/about_broker_filtering-xd7.html

Regards
William

Link to comment
  • 0

Hello --

I tried running the Get-BrokerSession from the PowerShell, version 2.0, console, but the error message that I am getting is the following:

The term 'Get-BrokerSession' is not recognized as the name of a cmlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

What would be the correct path to the cmdlet, or is this something that needs to be installed onto the server?

Thanks.

Link to comment
  • 0

Here's a script I created for killing off disconnected sessions. Basically it checks the state of each machine and then performs the action for that state.

 

For disconnected sessions it checks how long it's been in that state and if it's greater then 90 minutes restarts the session.

 

If you run it directly you get a summary in the window. I call it via a scheduled task on the controller every 30 minutes, I'll paste the batch file code at the bottom.

 

#------------------------------------------------------#

#

# FILE NAME - SessionCheckerV3.ps1

#
# Script that checks the session state of all powered desktops
# and performs the listed action for each state.
#
#------------------------------------------------------#

##Load Citrix modules if not already loaded
$snapins = Get-PSSnapin | where { $_.Name -like "Citrix*" }
if ($snapins -eq $null)
{
   Get-PSSnapin -Registered "Citrix*" | Add-PSSnapin
   Add-PSSnapin "PvsPsSnapin"
}

[int]$disconnected = 0
[int]$unregistered = 0
[int]$poweredon = 0
[int]$poweredoff = 0

foreach ($desktop in Get-BrokerDesktop -MaxRecordCount 10000)
{
 if ($desktop.PowerState -eq 'On')
 {
    $poweredon++

 
     if ($desktop.SummaryState -eq 'Unregistered')
     {
         #If powered-on and unregistered, perform a forceful restart
         #New-BrokerHostingPowerAction -MachineName $desktop.MachineName -Action Reset
        $temp = $desktop.MachineName            
         Write-Host "Unregistered: $temp"

        $unregistered++
     }
 
     if ($desktop.SummaryState -eq 'Disconnected')
     {
         #If powered-on and disconnected, check for sessions older than 90 minutes
         $timediff = (Get-Date) - $desktop.SessionStateChangeTime

            if ($timediff.TotalMinutes -gt 90)
            {
                # if in disconnected state for more then 90 minutes restart vm
                New-BrokerHostingPowerAction -MachineName $desktop.MachineName -Action Restart
            }
        
        $temp = $desktop.MachineName            
         Write-Host "Disconnected: $temp"
        
        $disconnected++
    }

    if ($desktop.SummaryState -eq 'Available')
    {
        #If powered-on and ready, perform a graceful restart
        #New-BrokerHostingPowerAction -MachineName $desktop.MachineName -Action Restart
    }
 }

 if ($desktop.PowerState -eq 'Off')
    {
        #If powered-off, turn it on
        #New-BrokerHostingPowerAction -MachineName $desktop.MachineName -Action TurnOn

        $poweredoff++
    }
}

 Write-Host " -------------------------------------"
 Write-Host " Powered On: $poweredon"
 Write-Host " Disconnected: $disconnected"
 Write-Host " Unregistered: $unregistered"
 Write-Host " Powered Off: $poweredoff"
 Write-Host " -------------------------------------"

 

************************************************************************************************************************************************

BATCH FILE - called via scheduled task

 

************************************************************************************************************************************************

 

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted -File "C:\Scripts\SessionCheckerV3.ps1"

Link to comment
  • 0

But how about this:

 

#———————————————————————

 

# Date : 13-08-2013
# Script name : Force_restart.ps1
# Description : Restart disconnected desktops after 9 hours. Only desktops of a desktop group will be restarted.
# PowerOff disconnected desktops after 10 hours. Only desktops of a desktop group will be restarted.
#
#
# Extra module : citrix*
VMware.VimAutomation.Core
VMware.VimAutomation.Vds
#
# Copyright : ©2014 Login Consultants, all rights reserved.
# History : RJA 20140812 Initial version
# RJA 20140813 PowerOff added
#———————————————————————

# Import the required Snap-ins

Add-PSSnapIn citrix*
Add-PSSnapIn VMware.VimAutomation.Core
Add-PSSnapIn VMware.VimAutomation.Vds
# Query all VDI desktops that are in maintenance mode longer then 9 hours.

$forcerebootmachines = Get-BrokerSession -SessionState Disconnected -Filter {SessionStateChangeTime -lt “-9:00″} -HypervisorConnectionName REPLACE WITH GROUP -DesktopGroupName “REPLACE WITH GROUP”| Select-Object HostedMachineName

foreach ($item in $forcerebootmachines)
{
Restart-Computer -Force -computername $item.HostedMachineName
}

# Shutdown VDI desktops that do not respond to restart-computer

$ConfirmPreference=”none”
Set-PowerCliConfiguration -invalidcertificateaction Ignore
Connect-VIServer REPLACE WITH VSPHERE SERVER -notdefault

$forcerebootmachines10 = Get-BrokerSession -SessionState Disconnected -Filter {SessionStateChangeTime -lt “-10:00″} -HypervisorConnectionName REPLACE WITH GROUP -DesktopGroupName “REPLACE WITH GROUP”| Select-Object HostedMachineName

foreach ($item in $forcerebootmachines10)
{
Get-VM -Name $item.HostedMachineName | Stop-VM -Kill
}

:)

Link to comment
  • 0

"..For disconnected sessions it checks how long it's been in that state and if it's greater then 90 minutes restarts the session"

 

Great but what if I only want to shut down the machine or logg of the user?

 

Really appreciate your answer

 

:)

 

 

Just change the -Action to TurnOff -

 

New-BrokerHostingPowerAction -MachineName $desktop.MachineName -Action TurnOff

 

Not sure about just logging them off but if it's a non-persistent desktop such as a pooled desktop you'd want to reboot it anyway to get it back to a clean state.

  • Like 1
Link to comment
  • 0
On 20/08/2014 at 4:34 PM, Paul Cross said:

 

 

Just change the -Action to TurnOff -

 

New-BrokerHostingPowerAction -MachineName $desktop.MachineName -Action TurnOff

 

Not sure about just logging them off but if it's a non-persistent desktop such as a pooled desktop you'd want to reboot it anyway to get it back to a clean state.

Can we add one more step in like if I want to logoff the sessions with disconnected session of one hours for a particular app like ABC  and send the results via email.

Link to comment
  • 0
On 8/20/2014 at 10:10 AM, Peter Fällman said:

"..For disconnected sessions it checks how long it's been in that state and if it's greater then 90 minutes restarts the session"

 

Great but what if I only want to shut down the machine or logg of the user?

 

Really appreciate your answer

 

?

Get-BrokerSession -MaxRecordCount 2000 | Select-Object BrokeringUserName, MachineName,  ClientAddress, Clientname, CatalogName, SessionStateChangeTime,  SessionState |  Where {$_.SessionStateChangeTime -lt (get-date).AddHours(-3)} | where SessionState -eq 'disconnected'                          

 

 

  more than 3 hours and the cession is disconnected

 

 

 

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...