Public/Get-CitrixMachineSessions.ps1

<#
.SYNOPSIS
    Retrieves Citrix session details for a specified machine.
 
.DESCRIPTION
    This function fetches information about all active sessions on a specified machine within a Citrix environment.
    It provides detailed session information including the session type, state, user details, and activity duration.
 
.PARAMETER AdminAddress
    Specifies the address of the Citrix administration server.
 
.PARAMETER MachineName
    Specifies the name of the machine to query for active sessions.
 
.EXAMPLE
    Get-CitrixMachineSessions -AdminAddress "ctx-admin.server.com" -MachineName "CTX01"
    Retrieves and displays session details for the Citrix machine named CTX01.
 
.NOTES
    Requires Citrix PowerShell SDK and appropriate administrative credentials.
#>


Function Get-CitrixMachineSessions {
    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    Param(
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string]$AdminAddress,
        
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string]$MachineName
    )
    
    Begin {
        $DateFormat = "\[dd/MM/yy HH:mm:ss\]"
        $DateTime = Get-Date -Format $DateFormat
    }
    
    Process {
        try {
            $CitrixParams = @{
                AdminAddress        = $AdminAddress
                MaxRecordCount      = [Int32]::MaxValue
                HostedMachineName   = $MachineName
                ErrorAction         = 'Stop'
            }

            $Sessions = Get-BrokerSession @CitrixParams
            
            if ($Sessions) {
                foreach ($Session in $Sessions) {
                    $TimeDifference = New-TimeSpan -Start $Session.StartTime -End (Get-Date)
                    $ActiveTime = "{0}h:{1:D2}m:{2:D2}s" -f $TimeDifference.Hours, $TimeDifference.Minutes, $TimeDifference.Seconds
                    [PSCustomObject]@{
                        Timestamp           = $DateTime
                        MachineName         = $MachineName
                        SessionType         = $Session.SessionType
                        SessionState        = $Session.SessionState
                        UserName            = $Session.UserName
                        UserFullName        = $Session.UserFullName
                        StartTime           = $Session.StartTime
                        ActiveDuration      = $ActiveTime
                        ClientIP            = $Session.ClientAddress
                    }
                }
            } else {
                Write-Output "There are currently no active sessions on the machine: $MachineName."
            }
        } catch {
            Write-Error "Error querying the sessions from $AdminAddress : $_"
        }
    }

    End {
        Write-Verbose "Query completed for machine: $MachineName."
    }
}