RDS User Disconnected Monitor and Action Script

<#
.SYNOPSIS
RDS User Disconnected Monitor and Action Script

.DESCRIPTION
This script monitors Remote Desktop Services for disconnected user sessions
and performs specified actions when a user disconnects.

.PARAMETER Action
The action to perform when a user disconnects. Options are 'Log', 'Logoff', or 'Both'.

.PARAMETER LogFile
The path of the log file where disconnect events will be recorded.

.EXAMPLE
.\RDSDisconnectMonitor.ps1 -Action "Log" -LogFile "C:\Logs\RDSDisconnects.log"

.NOTES
File Name      : RDSDisconnectMonitor.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V3 or later, admin rights on the RDS server
Version        : 1.0
Date           : [Current Date]
#>

param (
    [Parameter(Mandatory=$true)]
    [ValidateSet("Log", "Logoff", "Both")]
    [string]$Action,

    [Parameter(Mandatory=$true)]
    [string]$LogFile
)

# Function to write log entries
function Write-Log {
    param (
        [string]$Message
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "$timestamp - $Message"
    Add-Content -Path $LogFile -Value $logEntry
    Write-Host $logEntry
}

# Function to get disconnected sessions
function Get-DisconnectedSessions {
    $sessions = quser | Where-Object { $_ -match 'Disc' }
    $disconnectedUsers = @()
    foreach ($session in $sessions) {
        $sessionInfo = $session -split '\s+'
        $disconnectedUsers += [PSCustomObject]@{
            Username = $sessionInfo[1]
            SessionID = $sessionInfo[2]
        }
    }
    return $disconnectedUsers
}

# Function to perform action on disconnected session
function Perform-Action {
    param (
        [string]$Username,
        [string]$SessionID
    )

    switch ($Action) {
        "Log" {
            Write-Log "User disconnected: $Username (Session ID: $SessionID)"
        }
        "Logoff" {
            logoff $SessionID
            Write-Log "User logged off: $Username (Session ID: $SessionID)"
        }
        "Both" {
            Write-Log "User disconnected: $Username (Session ID: $SessionID)"
            logoff $SessionID
            Write-Log "User logged off: $Username (Session ID: $SessionID)"
        }
    }
}

# Create the log file if it doesn't exist
if (-not (Test-Path $LogFile)) {
    New-Item -Path $LogFile -ItemType File -Force
}

Write-Log "Starting RDS disconnect monitoring..."

# Main monitoring loop
try {
    $previousSessions = @()
    while ($true) {
        $currentSessions = Get-DisconnectedSessions
        
        # Check for new disconnections
        foreach ($session in $currentSessions) {
            if ($session.Username -notin $previousSessions.Username) {
                Perform-Action -Username $session.Username -SessionID $session.SessionID
            }
        }

        $previousSessions = $currentSessions
        Start-Sleep -Seconds 30  # Check every 30 seconds
    }
}
catch {
    Write-Log "An error occurred: $_"
}
finally {
    Write-Log "RDS disconnect monitoring stopped."
}

To use this script:

  1. Save it as RDSDisconnectMonitor.ps1.
  2. Open PowerShell as an administrator on the RDS server.
  3. Navigate to the directory containing the script.
  4. Run the script with the required parameters:

.\RDSDisconnectMonitor.ps1 -Action "Log" -LogFile "C:\Logs\RDSDisconnects.log"

You can replace “Log” with “Logoff” to automatically log off disconnected users, or “Both” to log and then log off.

Key features of this script:

  1. Monitoring: Continuously checks for disconnected RDS sessions.
  2. Flexible Actions: Can log disconnections, automatically log off disconnected users, or both.
  3. Logging: Records all actions and events to a specified log file.
  4. Customizable: Easy to modify for additional actions or different checking intervals.

Notes:

  • This script needs to be run with administrator privileges on the RDS server.
  • The script will continue running until manually stopped (e.g., by pressing Ctrl+C).
  • For production use, consider running this script as a Windows Service or scheduled task.
  • The script checks for disconnections every 30 seconds by default. You can adjust this interval by changing the Start-Sleep -Seconds 30 line.
  • Be cautious when using the “Logoff” action, as it will forcibly close user sessions, which might result in data loss if users have unsaved work.

This script provides a foundation for monitoring and managing disconnected RDS sessions. You can further customize it based on your specific requirements, such as sending notifications, integrating with other systems, or implementing more complex decision logic for when to log off users.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *