Public/Invoke-RemoteUserLogoff.ps1
<#
.SYNOPSIS Logs off a user session on a remote server. .DESCRIPTION This function logs off a user session on a specified remote server using the quser and logoff commands. .PARAMETER ComputerName The name of the remote server where the user session is to be logged off. .PARAMETER UserName The name of the user whose session is to be logged off. .EXAMPLE Invoke-RemoteUserLogoff -ComputerName "Server01" -UserName "User1" Logs off the session of "User1" on "Server01". .NOTES Author: Sundeep Eswarawaka #> Function Invoke-RemoteUserLogoff { Param ( [Parameter(Mandatory=$true, Position=0)] [string] $ComputerName, [Parameter(Mandatory=$true, Position=1)] [string] $UserName ) try { $quserResult = quser /server:$ComputerName 2>&1 if ($quserResult.Count -gt 0) { $quserRegex = $quserResult | ForEach-Object { $_ -replace '\s{2,}', ',' } $quserObject = $quserRegex | ConvertFrom-Csv $userSession = $quserObject | Where-Object { $_.USERNAME -eq $UserName } if ($userSession) { logoff $userSession.ID /server:$ComputerName Write-Output "$UserName session ($($userSession.ID)) logged off on $ComputerName" } else { Write-Output "No session found for $UserName on $ComputerName" } } else { Write-Output "No sessions found on $ComputerName" } } catch { Write-Output "Error: $_" } } |