-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGet-CurrentRDPSessions.ps1
More file actions
677 lines (591 loc) · 32.4 KB
/
Get-CurrentRDPSessions.ps1
File metadata and controls
677 lines (591 loc) · 32.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
#Requires -RunAsAdministrator
function Get-CurrentRDPSessions {
<#
.SYNOPSIS
Display current active RDP sessions on the system.
.DESCRIPTION
Shows currently logged-on RDP users, their session IDs, states, and processes.
Useful for real-time monitoring and quick session overview.
Use standard PowerShell filtering (Where-Object) to filter by specific sessions.
.PARAMETER ShowProcesses
Show running processes for each active session.
.PARAMETER Watch
Enable continuous monitoring mode with auto-refresh. Press Ctrl+C to exit.
.PARAMETER RefreshInterval
Refresh interval in seconds when using -Watch mode. Default is 5 seconds.
.PARAMETER LogPath
Path to write session change log file. Logs new connections, disconnections, and state changes.
Creates a timestamped CSV file for later analysis. Works in both single-check and Watch mode.
.EXAMPLE
Get-CurrentRDPSessions
Display all current RDP sessions.
.EXAMPLE
Get-CurrentRDPSessions -ShowProcesses
Show detailed information and processes for all active sessions.
.EXAMPLE
Get-CurrentRDPSessions | Where-Object { $_.ID -eq 3 }
Filter output to show only session ID 3 using standard PowerShell.
.EXAMPLE
Get-CurrentRDPSessions -Watch
Continuously monitor RDP sessions with 5-second refresh.
.EXAMPLE
Get-CurrentRDPSessions -Watch -RefreshInterval 10
Monitor sessions with 10-second refresh interval.
.EXAMPLE
Get-CurrentRDPSessions -Watch -LogPath "C:\Logs\RDP_Monitor"
Monitor sessions with logging enabled. Changes are written to CSV for later analysis.
.EXAMPLE
Get-CurrentRDPSessions -Watch -RefreshInterval 5 -LogPath "C:\SecurityLogs\RDP" -ShowProcesses
Full monitoring with process tracking and change logging for incident response.
.NOTES
Author: Jan Tiedemann
Version: 1.0.8
Requires: Administrator privileges
Changelog v1.0.8:
- Added Win32 API (WTS) integration for extended session properties
- New properties: IdleTime, ClientIPAddress, ClientName, EncryptionLevel
- New properties: ConnectTime, ClientBuildNumber, ClientDisplay, ColorDepth
- Improved accuracy without Event Log dependency for basic info
- ConnectTime uses multi-source event collection for accuracy:
* Security Events: 4778 (reconnection), 4624 (logon)
* Terminal Services Events: 25 (reconnection), 21/22 (session logon)
* Automatically uses most recent event across all sources
* Works with or without Security audit policies enabled
#>
[CmdletBinding()]
param(
[Parameter()]
[switch]$ShowProcesses,
[Parameter()]
[switch]$Watch,
[Parameter()]
[ValidateRange(1, 300)]
[int]$RefreshInterval = 5,
[Parameter()]
[string]$LogPath
)
# Win32 API Definitions for Windows Terminal Services (WTS)
# Only add type if not already loaded
if (-not ([System.Management.Automation.PSTypeName]'WTSApi').Type) {
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public enum WTS_CONNECTSTATE_CLASS
{
WTSActive,
WTSConnected,
WTSConnectQuery,
WTSShadow,
WTSDisconnected,
WTSIdle,
WTSListen,
WTSReset,
WTSDown,
WTSInit
}
public enum WTS_INFO_CLASS
{
WTSInitialProgram,
WTSApplicationName,
WTSWorkingDirectory,
WTSOEMId,
WTSSessionId,
WTSUserName,
WTSWinStationName,
WTSDomainName,
WTSConnectState,
WTSClientBuildNumber,
WTSClientName,
WTSClientDirectory,
WTSClientProductId,
WTSClientHardwareId,
WTSClientAddress,
WTSClientDisplay,
WTSClientProtocolType,
WTSIdleTime,
WTSLogonTime,
WTSIncomingBytes,
WTSOutgoingBytes,
WTSIncomingFrames,
WTSOutgoingFrames,
WTSClientInfo,
WTSSessionInfo,
WTSSessionInfoEx,
WTSConfigInfo,
WTSValidationInfo,
WTSSessionAddressV4,
WTSIsRemoteSession
}
[StructLayout(LayoutKind.Sequential)]
public struct WTS_SESSION_INFO
{
public int SessionId;
public IntPtr pWinStationName;
public WTS_CONNECTSTATE_CLASS State;
}
[StructLayout(LayoutKind.Sequential)]
public struct WTS_CLIENT_ADDRESS
{
public int AddressFamily;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public byte[] Address;
}
[StructLayout(LayoutKind.Sequential)]
public struct WTS_CLIENT_DISPLAY
{
public int HorizontalResolution;
public int VerticalResolution;
public int ColorDepth;
}
public class WTSApi
{
[DllImport("wtsapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool WTSEnumerateSessions(
IntPtr hServer,
int Reserved,
int Version,
out IntPtr ppSessionInfo,
out int pCount);
[DllImport("wtsapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool WTSQuerySessionInformation(
IntPtr hServer,
int sessionId,
WTS_INFO_CLASS wtsInfoClass,
out IntPtr ppBuffer,
out int pBytesReturned);
[DllImport("wtsapi32.dll")]
public static extern void WTSFreeMemory(IntPtr pMemory);
public static readonly IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;
}
"@
}
# Emoji support for both PowerShell 5.1 and 7.x
function Get-Emoji {
param([string]$Name)
if ($PSVersionTable.PSVersion.Major -ge 6) {
$emojis = @{
'computer' = [char]::ConvertFromUtf32(0x1F4BB)
'clock' = [char]::ConvertFromUtf32(0x23F1) + [char]::ConvertFromUtf32(0xFE0F)
'user' = [char]::ConvertFromUtf32(0x1F464)
'check' = [char]::ConvertFromUtf32(0x2705)
'warning' = [char]::ConvertFromUtf32(0x26A0) + [char]::ConvertFromUtf32(0xFE0F)
'chart' = [char]::ConvertFromUtf32(0x1F4CA)
}
}
else {
# PowerShell 5.1 - Use Unicode symbols that work in Windows Console
$emojis = @{
'computer' = "$([char]0x25A3)" # White square with rounded corners
'clock' = "$([char]0x25D4)" # Circle with upper right quadrant
'user' = "$([char]0x263A)" # White smiling face
'check' = "$([char]0x221A)" # Square root (checkmark-like)
'warning' = "$([char]0x203C)" # Double exclamation
'chart' = "$([char]0x25A0)" # Black square
}
}
return $emojis[$Name]
}
# Helper function to query WTS session information
function Get-WTSSessionInfo {
param(
[int]$SessionId,
[WTS_INFO_CLASS]$InfoClass
)
$buffer = [IntPtr]::Zero
$bytesReturned = 0
try {
$result = [WTSApi]::WTSQuerySessionInformation(
[WTSApi]::WTS_CURRENT_SERVER_HANDLE,
$SessionId,
$InfoClass,
[ref]$buffer,
[ref]$bytesReturned
)
if ($result -and $buffer -ne [IntPtr]::Zero) {
switch ($InfoClass) {
([WTS_INFO_CLASS]::WTSClientAddress) {
$clientAddr = [System.Runtime.InteropServices.Marshal]::PtrToStructure($buffer, [Type][WTS_CLIENT_ADDRESS])
if ($clientAddr.AddressFamily -eq 2) {
# AF_INET (IPv4)
return "$($clientAddr.Address[2]).$($clientAddr.Address[3]).$($clientAddr.Address[4]).$($clientAddr.Address[5])"
}
return "Unknown"
}
([WTS_INFO_CLASS]::WTSClientDisplay) {
$display = [System.Runtime.InteropServices.Marshal]::PtrToStructure($buffer, [Type][WTS_CLIENT_DISPLAY])
return [PSCustomObject]@{
Width = $display.HorizontalResolution
Height = $display.VerticalResolution
ColorDepth = $display.ColorDepth
}
}
([WTS_INFO_CLASS]::WTSIdleTime) {
$idleTime = [System.Runtime.InteropServices.Marshal]::ReadInt64($buffer)
return $idleTime
}
([WTS_INFO_CLASS]::WTSLogonTime) {
$logonTime = [System.Runtime.InteropServices.Marshal]::ReadInt64($buffer)
if ($logonTime -gt 0) {
return [DateTime]::FromFileTime($logonTime)
}
return $null
}
([WTS_INFO_CLASS]::WTSClientBuildNumber) {
return [System.Runtime.InteropServices.Marshal]::ReadInt32($buffer)
}
default {
# String properties - use Unicode marshaling
return [System.Runtime.InteropServices.Marshal]::PtrToStringUni($buffer)
}
}
}
return $null
}
finally {
if ($buffer -ne [IntPtr]::Zero) {
[WTSApi]::WTSFreeMemory($buffer)
}
}
}
# Initialize logging if LogPath is specified
$logFile = $null
$previousSessions = @{}
if ($LogPath) {
# Create log directory if it doesn't exist
if (-not (Test-Path $LogPath)) {
New-Item -Path $LogPath -ItemType Directory -Force | Out-Null
}
# Create timestamped log file
$timestamp = Get-Date -Format 'yyyyMMdd_HHmmss'
$logFile = Join-Path $LogPath "RDP_SessionMonitor_$timestamp.csv"
# Write CSV header with extended properties
"Timestamp,EventType,SessionName,Username,SessionID,State,ClientIP,ClientName,ConnectTime,ClientBuild,IdleTime,Details" | Out-File -FilePath $logFile -Encoding UTF8
Write-Host "$(Get-Emoji 'chart') Logging enabled: " -ForegroundColor Cyan -NoNewline
Write-Host "$logFile" -ForegroundColor Green
Write-Host ""
}
# Main monitoring logic wrapped in a loop for Watch mode
$continueMonitoring = $true
$iterationCount = 0
while ($continueMonitoring) {
# Clear screen only in Watch mode (after first iteration)
if ($Watch -and $iterationCount -gt 0) {
Clear-Host
}
# ASCII Art Header - Use basic ASCII for PowerShell 5.1 compatibility
Write-Host "`n" -NoNewline
Write-Host ("=" * 53) -ForegroundColor Green
Write-Host " ACTIVE RDP SESSIONS MONITOR v1.0.8 " -ForegroundColor White
Write-Host ("=" * 53) -ForegroundColor Green
Write-Host ""
Write-Host "$(Get-Emoji 'computer') Computer: " -ForegroundColor Cyan -NoNewline
Write-Host "$env:COMPUTERNAME" -ForegroundColor White
Write-Host "$(Get-Emoji 'clock') Time: " -ForegroundColor Cyan -NoNewline
Write-Host "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor White
if ($Watch) {
Write-Host "$(Get-Emoji 'check') Mode: " -ForegroundColor Cyan -NoNewline
Write-Host "Auto-Refresh (${RefreshInterval}s) - Press Ctrl+C to exit" -ForegroundColor Yellow
}
Write-Host ""
# Get current sessions using qwinsta (reliable) + WTS API for extended properties
try {
$sessions = qwinsta 2>$null
if ($sessions) {
# Parse qwinsta output
$sessionObjects = @()
foreach ($line in $sessions | Select-Object -Skip 1) {
if ($line -match '^\s*>?\s*(\S+)\s+(\S+|\s+)\s+(\d+)\s+(\S+)') {
$sessionName = $matches[1].Trim()
$username = $matches[2].Trim()
$id = [int]$matches[3].Trim()
$state = $matches[4].Trim()
# Only include active/disconnected RDP sessions
# Exclude: console (local), services (system), Listen states (RDP listeners)
# Include: rdp-tcp#X sessions with Active/Disc/Conn states
if ($sessionName -match 'rdp-tcp#\d+' -and $state -notmatch 'Listen') {
# Use WTS API to get extended session properties
$clientName = Get-WTSSessionInfo -SessionId $id -InfoClass ([WTS_INFO_CLASS]::WTSClientName)
# Filter out invalid client names (empty, whitespace, or non-ASCII junk)
if ($clientName -and $clientName.Trim() -ne '' -and $clientName -match '^[\x20-\x7E]+$') {
$clientName = $clientName.Trim()
}
else {
$clientName = $null
}
$clientIP = Get-WTSSessionInfo -SessionId $id -InfoClass ([WTS_INFO_CLASS]::WTSClientAddress)
$clientBuild = Get-WTSSessionInfo -SessionId $id -InfoClass ([WTS_INFO_CLASS]::WTSClientBuildNumber)
$clientDisplay = Get-WTSSessionInfo -SessionId $id -InfoClass ([WTS_INFO_CLASS]::WTSClientDisplay)
$idleTime = Get-WTSSessionInfo -SessionId $id -InfoClass ([WTS_INFO_CLASS]::WTSIdleTime)
$wtsConnectTime = Get-WTSSessionInfo -SessionId $id -InfoClass ([WTS_INFO_CLASS]::WTSLogonTime)
# Always check Event Log for most accurate connection time
# WTS API may return stale data for new sessions after logoff/logon
$eventLogConnectTime = $null
if ($username -and $username -ne '') {
# Collect all potential connection events and use the most recent one
$candidateEvents = @()
# Check Security Event 4778 (reconnection)
$reconnectEvent = Get-WinEvent -FilterHashtable @{
LogName = 'Security'
Id = 4778
} -MaxEvents 50 -ErrorAction SilentlyContinue | Where-Object {
$_.Message -match [regex]::Escape($username)
} | Select-Object -First 1
if ($reconnectEvent) {
$candidateEvents += $reconnectEvent
}
# Check Terminal Services Event 25 (reconnection)
$tsReconnect = Get-WinEvent -FilterHashtable @{
LogName = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
Id = 25
} -MaxEvents 50 -ErrorAction SilentlyContinue | Where-Object {
$_.Message -match [regex]::Escape($username) -and
$_.Properties[0].Value -eq $id # Session ID
} | Select-Object -First 1
if ($tsReconnect) {
$candidateEvents += $tsReconnect
}
# Check Security Event 4624 (initial logon)
$logonEvent = Get-WinEvent -FilterHashtable @{
LogName = 'Security'
Id = 4624
} -MaxEvents 100 -ErrorAction SilentlyContinue | Where-Object {
$_.Message -match [regex]::Escape($username) -and
$_.Message -match 'Logon Type:\s+(10|7)\s' -and
($clientIP -and $_.Message -match [regex]::Escape($clientIP))
} | Select-Object -First 1
if ($logonEvent) {
$candidateEvents += $logonEvent
}
# Check Terminal Services Event 21 (session logon) or 22 (shell start)
$tsLogon = Get-WinEvent -FilterHashtable @{
LogName = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
Id = 21, 22
} -MaxEvents 100 -ErrorAction SilentlyContinue | Where-Object {
$_.Message -match [regex]::Escape($username) -and
$_.Properties[0].Value -eq $id # Session ID
} | Select-Object -First 1
if ($tsLogon) {
$candidateEvents += $tsLogon
}
# Use the most recent event from all candidates
if ($candidateEvents.Count -gt 0) {
$mostRecentEvent = $candidateEvents | Sort-Object TimeCreated -Descending | Select-Object -First 1
$eventLogConnectTime = $mostRecentEvent.TimeCreated
}
}
# Use the most recent time between WTS API and Event Log
# This handles cases where WTS returns stale data
$connectTime = if ($eventLogConnectTime -and $wtsConnectTime) {
# Both available - use most recent
if ($eventLogConnectTime -gt $wtsConnectTime) { $eventLogConnectTime } else { $wtsConnectTime }
}
elseif ($eventLogConnectTime) {
# Only Event Log available
$eventLogConnectTime
}
elseif ($wtsConnectTime) {
# Only WTS available
$wtsConnectTime
}
else {
# No time available
$null
}
# Calculate idle time in readable format
$idleTimeDisplay = if ($idleTime -ne $null -and $idleTime -ge 0) {
$idleMinutes = [Math]::Floor($idleTime / 60000)
if ($idleMinutes -lt 1) { "<1 min" }
elseif ($idleMinutes -lt 60) { "$idleMinutes min" }
else { "$([Math]::Floor($idleMinutes / 60))h $($idleMinutes % 60)m" }
}
else { "N/A" }
$sessionObjects += [PSCustomObject]@{
SessionName = $sessionName
Username = if ($username -and $username -ne '') { $username } else { 'N/A' }
ID = $id
State = $state
Type = 'RDP'
ClientName = if ($clientName) { $clientName } else { 'N/A' }
ClientIP = if ($clientIP) { $clientIP } else { 'Unknown' }
ClientBuild = if ($clientBuild) { $clientBuild } else { 'N/A' }
ClientDisplay = if ($clientDisplay) { "$($clientDisplay.Width)x$($clientDisplay.Height) ($($clientDisplay.ColorDepth)bit)" } else { 'N/A' }
IdleTime = $idleTimeDisplay
ConnectTime = if ($connectTime) { $connectTime } else { $null }
}
}
}
}
}
# Log changes if logging is enabled
if ($logFile -and $iterationCount -gt 0) {
$currentSessionKeys = @{}
foreach ($session in $sessionObjects) {
$key = "$($session.SessionName)-$($session.ID)"
$currentSessionKeys[$key] = $session
# Check for new sessions or state changes
if (-not $previousSessions.ContainsKey($key)) {
# New session detected
$connectTimeStr = if ($session.ConnectTime) { $session.ConnectTime.ToString('yyyy-MM-dd HH:mm:ss') } else { 'N/A' }
$logEntry = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'),NEW_SESSION,$($session.SessionName),$($session.Username),$($session.ID),$($session.State),$($session.ClientIP),$($session.ClientName),$connectTimeStr,$($session.ClientBuild),$($session.IdleTime),New RDP session detected"
$logEntry | Out-File -FilePath $logFile -Append -Encoding UTF8
Write-Host " [LOG] New session: $($session.Username) from $($session.ClientIP) (ID: $($session.ID))" -ForegroundColor Green
}
elseif ($previousSessions[$key].State -ne $session.State) {
# State change detected
$connectTimeStr = if ($session.ConnectTime) { $session.ConnectTime.ToString('yyyy-MM-dd HH:mm:ss') } else { 'N/A' }
$logEntry = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'),STATE_CHANGE,$($session.SessionName),$($session.Username),$($session.ID),$($session.State),$($session.ClientIP),$($session.ClientName),$connectTimeStr,$($session.ClientBuild),$($session.IdleTime),State changed from $($previousSessions[$key].State) to $($session.State)"
$logEntry | Out-File -FilePath $logFile -Append -Encoding UTF8
Write-Host " [LOG] State change: $($session.Username) - $($previousSessions[$key].State) -> $($session.State)" -ForegroundColor Yellow
}
}
# Check for disconnected/removed sessions
foreach ($key in $previousSessions.Keys) {
if (-not $currentSessionKeys.ContainsKey($key)) {
$oldSession = $previousSessions[$key]
$connectTimeStr = if ($oldSession.ConnectTime) { $oldSession.ConnectTime.ToString('yyyy-MM-dd HH:mm:ss') } else { 'N/A' }
$logEntry = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'),SESSION_ENDED,$($oldSession.SessionName),$($oldSession.Username),$($oldSession.ID),$($oldSession.State),$($oldSession.ClientIP),$($oldSession.ClientName),$connectTimeStr,$($oldSession.ClientBuild),$($oldSession.IdleTime),Session ended or disconnected"
$logEntry | Out-File -FilePath $logFile -Append -Encoding UTF8
Write-Host " [LOG] Session ended: $($oldSession.Username) from $($oldSession.ClientIP) (ID: $($oldSession.ID))" -ForegroundColor Red
}
}
# Update previous sessions tracking
$previousSessions = $currentSessionKeys
}
elseif ($logFile -and $iterationCount -eq 0) {
# First iteration - just record initial state
foreach ($session in $sessionObjects) {
$key = "$($session.SessionName)-$($session.ID)"
$previousSessions[$key] = $session
$connectTimeStr = if ($session.ConnectTime) { $session.ConnectTime.ToString('yyyy-MM-dd HH:mm:ss') } else { 'N/A' }
$logEntry = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'),INITIAL_STATE,$($session.SessionName),$($session.Username),$($session.ID),$($session.State),$($session.ClientIP),$($session.ClientName),$connectTimeStr,$($session.ClientBuild),$($session.IdleTime),Monitoring started - session already active"
$logEntry | Out-File -FilePath $logFile -Append -Encoding UTF8
}
}
if ($sessionObjects.Count -gt 0) {
Write-Host "`n" -NoNewline
Write-Host ("-" * 80) -ForegroundColor DarkGreen
Write-Host "$(Get-Emoji 'user') ACTIVE SESSIONS (" -ForegroundColor Yellow -NoNewline
Write-Host "$($sessionObjects.Count)" -ForegroundColor White -NoNewline
Write-Host ")" -ForegroundColor Yellow
Write-Host ("-" * 80) -ForegroundColor DarkGreen
# Display sessions with extended properties
$sessionObjects | Select-Object SessionName, Username, ID, State, ClientIP, ClientName, ConnectTime, IdleTime, ClientBuild, ClientDisplay | Format-Table -AutoSize
# Show processes for all sessions if requested
if ($ShowProcesses) {
foreach ($session in $sessionObjects) {
Write-Host "`n$(Get-Emoji 'computer') Processes for Session " -ForegroundColor Yellow -NoNewline
Write-Host "$($session.ID)" -ForegroundColor White -NoNewline
Write-Host " - User: " -ForegroundColor Yellow -NoNewline
Write-Host "$($session.Username)" -ForegroundColor Cyan
try {
$processes = qprocess /id:$($session.ID) 2>$null
if ($processes) {
$processes | Select-Object -Skip 1 | ForEach-Object {
Write-Host " $_" -ForegroundColor Gray
}
}
else {
Write-Host " No processes found or unable to query" -ForegroundColor Gray
}
}
catch {
Write-Host " Error querying processes: $_" -ForegroundColor Red
}
}
}
# Get recent logon events for active users
Write-Host "`n" -NoNewline
Write-Host ("-" * 80) -ForegroundColor DarkGreen
Write-Host "$(Get-Emoji 'chart') RECENT LOGON INFORMATION" -ForegroundColor Yellow
Write-Host ("-" * 80) -ForegroundColor DarkGreen
foreach ($session in $sessionObjects | Where-Object { $_.Username -ne 'N/A' }) {
# Collect all potential connection events and use the most recent one (same logic as ConnectTime)
$candidateEvents = @()
# Check Security Event 4778 (reconnection)
$reconnectEvent = Get-WinEvent -FilterHashtable @{
LogName = 'Security'
Id = 4778
} -MaxEvents 50 -ErrorAction SilentlyContinue | Where-Object {
$_.Message -match [regex]::Escape($session.Username)
} | Select-Object -First 1
if ($reconnectEvent) {
$candidateEvents += $reconnectEvent
}
# Check Terminal Services Event 25 (reconnection)
$tsReconnect = Get-WinEvent -FilterHashtable @{
LogName = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
Id = 25
} -MaxEvents 50 -ErrorAction SilentlyContinue | Where-Object {
$_.Message -match [regex]::Escape($session.Username) -and
$_.Properties[0].Value -eq $session.ID # Session ID
} | Select-Object -First 1
if ($tsReconnect) {
$candidateEvents += $tsReconnect
}
# Check Security Event 4624 (initial logon)
$logonEvent = Get-WinEvent -FilterHashtable @{
LogName = 'Security'
Id = 4624
} -MaxEvents 100 -ErrorAction SilentlyContinue | Where-Object {
$_.Message -match [regex]::Escape($session.Username) -and
$_.Message -match 'Logon Type:\s+(10|7)\s' -and
($session.ClientIP -and $_.Message -match [regex]::Escape($session.ClientIP))
} | Select-Object -First 1
if ($logonEvent) {
$candidateEvents += $logonEvent
}
# Check Terminal Services Event 21 (session logon) or 22 (shell start)
$tsLogon = Get-WinEvent -FilterHashtable @{
LogName = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
Id = 21, 22
} -MaxEvents 100 -ErrorAction SilentlyContinue | Where-Object {
$_.Message -match [regex]::Escape($session.Username) -and
$_.Properties[0].Value -eq $session.ID # Session ID
} | Select-Object -First 1
if ($tsLogon) {
$candidateEvents += $tsLogon
}
# Use the most recent event from all candidates
if ($candidateEvents.Count -gt 0) {
$recentActivity = $candidateEvents | Sort-Object TimeCreated -Descending | Select-Object -First 1
$sourceIP = if ($recentActivity.Message -match '(Source Network Address|Client Address):\s+([^\r\n]+)') {
$matches[2].Trim()
}
else {
'N/A'
}
$activityType = switch ($recentActivity.Id) {
4778 { "Last activity (reconnect)" }
4624 { "Last logon" }
25 { "Last activity (reconnect)" }
{ $_ -in 21, 22 } { "Last session activity" }
default { "Last activity" }
}
Write-Host " $(Get-Emoji 'check') " -ForegroundColor Green -NoNewline
Write-Host "$($session.Username)" -ForegroundColor Cyan -NoNewline
Write-Host " - $activityType" -ForegroundColor Gray -NoNewline
Write-Host ": $($recentActivity.TimeCreated)" -ForegroundColor White -NoNewline
Write-Host " from " -ForegroundColor Gray -NoNewline
Write-Host "$sourceIP" -ForegroundColor Yellow
}
}
}
else {
Write-Host "$(Get-Emoji 'warning') No active RDP sessions found." -ForegroundColor Yellow
}
}
catch {
Write-Error "Error getting session information: $_"
}
Write-Host ""
# Handle Watch mode loop
if ($Watch) {
$iterationCount++
Write-Host "Next refresh in $RefreshInterval seconds..." -ForegroundColor DarkGray
Start-Sleep -Seconds $RefreshInterval
}
else {
$continueMonitoring = $false
}
}
}