XenApp PowerShell Scripting with Get-XASession

I was working on a PowerShell script in XenApp today to quickly view active sessions by user, server, application, and session duration. Having focused most of my PoSH time in recent years to the XenDesktop SDK, I was somewhat disappointed with the limited flexibility (and official documentation) of the XenApp SDK, specifically with the Get-XASession cmdlet.

My main complaint is that Get-XASession doesn’t have many ‘Required’ parameters, which means that queries are limited to a subset of session details:


For example, if I want to find all sessions that are ‘Active’, I have to pipe the results of Get-XASession and evaluate each returned object. So, the following pipeline evaluation is required if you wanted to see all active sessions:

Get-XASession | Where-Object { $_.State -match 'Active'}

Using this as a foundation to find Active sessions, I took it a step further by using an input parameter (application name) to list sessions by application, and then formatted the output of the session details to get me what I’m looking for:

param ([String]$app)
foreach ($session in (Get-XASession | Where-Object { 
$_.BrowserName -match $app -and $_.State -match 'Active'} | 
select AccountName, ServerName, LogonTime, ConnectTime, CurrentTime, SessionID | 
Sort-Object LogonTime -Descending))
 $logon = (Get-Date) - $session.LogOnTime
 $connect = (Get-Date) - $session.ConnectTime
 "$($session.AccountName) logged on to $($session.ServerName) {0:00}:{1:00}:{2:00}" 
 -f $logon.Hours,$logon.Minutes,$logon.Seconds + " ago."

This script returns a active sessions by user name, connected to $app, the server on which it’s running, and the elapsed time (in ascending order) since they logged on (just subtract the $_.LogonTime date/time object from Get-Date). Notice how the $session object is compiled of properties of the sorted Get-XASession output by way of piping the output through several filters, which lets you create your own objects that can be easily manipulated and cross-referenced in the script. I also did some date/time formatting with {0:00}:{1:00}:{2:00}” -f $logon.Hours,$logon.Minutes,$logon.Seconds, though you can present this time duration in any way that makes sense.

Well, I hope this was worth a quick read, have a good weekend!