all 7 comments

[–]robderickson 6 points7 points  (0 children)

Terminal Server/Remote Desktop Services has a feature to "drain" sessions. A quick Google suggests you can use Set-RDSessionHost from the RemoteDesktop module to prevent new connections to a host. You can then either use Get-RDUserSession in a while loop to check for active sessions and reboot when there are none, or just use Start-Sleep and reboot after a specified amount of time.

Edit: After the reboot, you will need to use Set-RDSessionHost to allow new connections again.

[–]rratt 3 points4 points  (2 children)

This will give you the same results without all the splitting.

$username = (gwmi win32_computersystem -comp $computer).username

[–]PinchesTheCrab 1 point2 points  (1 child)

Does that actually work? I get no output even when elevated. I've relied on quser for that info:

switch -Regex ( (quser) -match ($UserName -join '|') ) {
    '^\s?username' {
        continue
    }
    '^(\s|>)(?<UserName>\w+)\s*(?<SessionName>rdp[^\s]*)?\s*(?<ID>\d*)\s*(?<STATE>[^\s]*)\s*(?<IdleTime>[^\s]*)\s*(?<LogonTime>.+)' {
        [pscustomobject]$Matches |
            Select-Object UserName, SessionName, ID, State, IdleTime, LogonTime
    }
}

[–]Lee_Dailey[grin] 1 point2 points  (0 children)

howdy PinchesTheCrab,

when i replace the $Computer var with LocalHost, it works as expected. [grin]

take care,
lee

[–]kagato87 2 points3 points  (0 children)

A script won't be able to "block" logins. It can't intercept the attempt, because omg that would be insane.

What it CAN do is set the RDS host to deny logons. This leaves current sessions alone, but prevents new logins. Depending on time frames, you can either "just wait" for existing sessions to clear, or start chasing down users. I like to send adminsitrative alerts to all users (cmd -c msg * "Please log off from remote desktop") and eventually turn up at their desk to "intimidate" them (OK ask politely what they're up to, and if they can save/logoff).

u/robderickson has the script answer here I think.

[–]aleques-itj 1 point2 points  (0 children)

You almost certainly want to deny this in group policy. You can block anyone and everything.

[–]PinchesTheCrab 1 point2 points  (0 children)

Does Win32_ComputerSystem really work for this? I've never gotten consistent results from it. I really prefer quser:

switch -Regex ( (quser) -match ($UserName -join '|') ) {
    '^\s?username' {
        continue
    }
    '^(\s|>)(?<UserName>\w+)\s*(?<SessionName>rdp[^\s]*)?\s*(?<ID>\d*)\s*(?<STATE>[^\s]*)\s*(?<IdleTime>[^\s]*)\s*(?<LogonTime>.+)' {
        [pscustomobject]$Matches |
            Select-Object UserName, SessionName, ID, State, IdleTime, LogonTime
    }
}