Continuing on my previous post Get Session Count over multiple NST’s I decided to make a little PowerShell function of it.

function Get-NAVServerSessions
{
Add-Type -TypeDefinition @"
   public enum ClientType
   {
      WindowsClient,
      SharePointClient,
      WebService,
      ClientService,
      NAS,
      Background,
      ManagementClient,
      WebClient,
      Unknown
   }
"@

$qry = "
DECLARE @command VARCHAR(MAX);
create table #temptable (
  [Database Name] nvarchar(250) not null,
  [Server Instance ID] int not null,
  [Session ID] int not null,
  [User ID] varchar(132) not null,
  [ClientType] int not null,
  [Login Datetime] datetime not null,
  [Client Computer Name] nvarchar(250) not null,
  [User SID] uniqueidentifier not null,
  [Server Instance Name] nvarchar(250) not null,
  [Server Computer Name] nvarchar(250) not null,
  [Tenant ID]  nvarchar(128) not null
);
 
set @command = 'use [?] IF OBJECT_ID (N''Active Session'', N''U'') IS NOT NULL insert into #temptable select ''?'',[Server Instance ID],[Session ID],[User ID],[Client Type],[Login Datetime],[Client Computer Name],[User SID],[Server Instance Name],[Server Computer Name],(select tenantid from dbo.[`$ndo`$tenantproperty]) from [Active Session]'
 
exec sp_MSforeachdb @command
 
select * from #temptable
drop table #temptable
"

$sessions = Invoke-Sqlcmd -query $qry -ServerInstance . -Database master
$sessions | Add-Member -MemberType NoteProperty -Name "Client Type" -Value ""
$sessions | foreach { $_."Client Type"=[Enum]::ToObject([ClientType],$_.ClientType)}
$sessions = $sessions | Select-Object -Property * -ExcludeProperty ClientType, RowState, RowError, Table, HasErrors, ItemArray
$sessions

}

The function is called “Get-NAVServerSessions”, so with an extra s at the end. It read all properties from the active session table, and also adds the tenant id for each database.

You should be able to add parameters to filter out specific sessions.