Public/Get-CitrixUserSessions.ps1
<#
.SYNOPSIS Retrieves active Citrix session details for a specified user, including session duration. .DESCRIPTION This function fetches detailed information about the active Citrix sessions for a given user, including session type, state, machine name, duration of activity or inactivity, and the formatted time difference since the session started. .PARAMETER AdminAddress The address of the Citrix Administration server. .PARAMETER UserName The user name or user principal name (UPN) to query the session information. .PARAMETER SamAccountName Specifies that the UserName parameter should be interpreted as the SAM account name. .PARAMETER Email Specifies that the UserName parameter should be interpreted as the email address (UPN). .EXAMPLE Get-CitrixUserSessions -AdminAddress "ctx-admin.domain.com" -UserName "jdoe" -SamAccountName Retrieves session details for the user with SAM account name 'jdoe', including how long each session has been active. .EXAMPLE Get-CitrixUserSessions -AdminAddress "ctx-admin.domain.com" -UserName "jdoe@domain.com" -Email Retrieves session details for the user with UPN 'jdoe@domain.com', including the duration of each session. .NOTES Requires Citrix PowerShell SDK and administrative rights to the Citrix environment. #> Function Get-CitrixUserSessions { [CmdletBinding()] [OutputType([PSCustomObject])] Param( [Parameter(Mandatory = $true)] [string]$AdminAddress, [Parameter(Mandatory = $true)] [string]$UserName, [Parameter()] [switch]$SamAccountName, [Parameter()] [switch]$Email ) Process { try { $filterExpression = if ($SamAccountName) { "UserName -eq '$UserName' -and Protocol -ne 'RDP'" } elseif ($Email) { "UserUPN -eq '$UserName' -and Protocol -ne 'RDP'" } else { throw "You must specify either -SamAccountName or -Email switch." } $sessions = Get-BrokerSession -AdminAddress $AdminAddress -MaxRecordCount ([Int32]::MaxValue) -Filter $filterExpression if ($sessions) { foreach ($session in $sessions) { $startTime = $session.StartTime $currentTime = Get-Date $timeDiff = New-TimeSpan -Start $startTime -End $currentTime if ($timeDiff.TotalHours -ge 24) { $formattedTime = "{0}d:{1}h:{2:D2} m:{3:D2}s" -f $timeDiff.Days, $timeDiff.Hours, $timeDiff.Minutes, $timeDiff.Seconds } elseif ($timeDiff.TotalMinutes -ge 60) { $formattedTime = "{0}h:{1:D2} m:{2:D2}s" -f $timeDiff.Hours, $timeDiff.Minutes, $timeDiff.Seconds } else { $formattedTime = "{0}m:{1:D2}s" -f $timeDiff.Minutes, $timeDiff.Seconds } [PSCustomObject]@{ UserName = $UserName HostedMachineName = $session.HostedMachineName SessionType = $session.SessionType SessionState = $session.SessionState StartTime = $session.StartTime Duration = $formattedTime ClientIP = $session.ClientAddress } } } else { Write-Output "There are currently no active Citrix sessions for user: $UserName." } } catch { Write-Error "Error querying the sessions from $AdminAddress : $_" } } } |