Tuesday, 1 April 2014

PowerShell – Log off all remote sessions

Needed to have a script that would log off all remote sessions from a given machine. The task is simple. The qwinsta commandlet lists all sessions and rwinsta logs off the session. I couldn’t find a script anywhere that would use the two together, so wrote the following. Enjoy!!

param (
    [String]$computer
)
$sessions = qwinsta /server:$computer
$sessions = $sessions[1..$($sessions.Count - 1)]
foreach ($Result in $sessions) {
    $userName = $Result.Substring(19,22).Trim()
    $id = $Result.Substring(41,7).Trim()                        
    if ($userName -ne ""){
                    rwinsta /server:$computer $id

    }
}   

Technorati Tags: ,

1 comment:

h said...

Hamid, thanks for your code--it worked much better for me than using disconnect-rdsession and other similar powershell methods.

I adapted your code to logoff a single user from every server on the network, which I find really useful to prevent account lockouts when an admin password changes. Here's my script: https://nonprofittechy.blogspot.com/2016/09/logoff-specific-user-from-all-servers.html