Friday, February 13, 2015

Automatic log off RDP users


# This script will log off any RDP users with names that contains "user" that have been disconnected for over 30 minutes
# 


$idteTimeOut = 30 # enter time in minutes only
$rdpUser = "user" # enter name string for searching

function RemoveSpace([string]$text) {  
    $private:array = $text.Split(" ", `
    [StringSplitOptions]::RemoveEmptyEntries)
    [string]::Join(" ", $array) }

# Quser - displays information about user sessions on a Remote Desktop Session Host (RD Session Host) server.
$quser = quser
foreach ($sessionString in $quser) {
    $sessionString = RemoveSpace($sessionString)
    $session = $sessionString.split()
    #$session[0] contains USERNAME
    If ($session[0].Contains($rdpUser)) { 
        #$session[2] contains STATE, there is no SESSIONNAME for Disconnected user
        If ($session[2].Equals("Disc")) {
            #Write-Output $session[0]
            # $session[3] contains TIME, there is no SESSIONNAME for Disconnected user
            # Check TIME string if is less than a min make it 0
            If ($session[3].Contains(".")) {
                $session[3] = "0"
            }
            
            # Convert TIME string into h:m format string
            If (!($session[3].Contains(":"))) {
                $session[3] = "0:" + $session[3]
            }
            # Convert TIME string minutes(using timespan) into a number
            $strNum = ([timespan]$session[3] | % {$_.TotalMinutes})
            [int]$intNum = [convert]::ToInt32($strNum, 10)
                # If the number of minutes is greater than idle time-out log off user
                If ($intNum -gt $idteTimeOut) {
                # $session[1] contains ID for logoff command, there is no SESSIONNAME for Disconnected user 
                $Result = logoff $session[1]
                }
        }
    }
    }
$quser = quser
Write-Output $quser


No comments:

Post a Comment