Skip to content

Instantly share code, notes, and snippets.

@radleta
Created February 12, 2025 13:37
Show Gist options
  • Save radleta/1203fa2a8bcdcf4baffb7fb1e75662ee to your computer and use it in GitHub Desktop.
Save radleta/1203fa2a8bcdcf4baffb7fb1e75662ee to your computer and use it in GitHub Desktop.
Logs off a disconnected user session from a remote server.
<#
.SYNOPSIS
Logs off a disconnected user session from a remote server.
.DESCRIPTION
This script retrieves the session list from a specified remote server,
parses the session information, and logs off the specified user if their
session is found to be disconnected.
.PARAMETER server
The name or IP address of the remote server.
.PARAMETER userToLogOff
The username of the user to log off.
.PARAMETER debug
Switch to enable debug output for detailed information during execution.
.EXAMPLE
.\LogOffDiscUser.ps1 -server "machine_name_goes_here" -userToLogOff "ntusername_goes_here" -debug
.NOTES
Author: Richard Adleta
Date: Feb 12, 2025
#>
param (
[string]$server,
[string]$userToLogOff,
[switch]$debug
)
# Get the session list from the remote machine
$sessions = qwinsta /SERVER:$server 2>$null
if (-not $sessions) {
Write-Host "Failed to retrieve session information from $server"
exit 1
}
# Parse session output
$sessions | ForEach-Object {
$line = $_ -replace '\s+', ' ' # Normalize spaces
$fields = $line -split ' '
# Diagnostic output
if ($debug) {
Write-Host "Parsing line: $line"
Write-Host "Fields: $($fields.Count)"
}
# Check if the line contains the expected number of fields
if ($fields.Count -ge 4) {
$sessionId = $fields[2] # Session ID is typically at index 2
$sessionState = $fields[3] # Last field is usually the session state
$userName = $fields[1] # User is usually at index 1
# Diagnostic output
if ($debug) {
Write-Host "Session ID: $sessionId, User: $userName, State: $sessionState"
}
# Check if the session belongs to the target user and is disconnected
if ($userName -eq $userToLogOff -and $sessionState -eq "Disc") {
Write-Host "Logging off user $userToLogOff on session ID $sessionId"
rwinsta /SERVER:$server $sessionId
exit 0
}
}
}
Write-Host "No disconnected session found for user $userToLogOff on $server"
exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment