Enable Users to log off their own RDP TS session with PowerShell
24. November 2015
PowerShell Version: >1
Modules: none
This script will check your TS servers for a session with $env:Username and logoff that session. This of course only works if $env:username on client and TS are the same 😉 Also I made an effort to make it work on PS v1 for all clients to be able to execute this.
# mention all terminal servers here $server1 = "SERVER1-FQDN" $server2 = "SERVER2-FQDN" # build an array for the foreach $ts_server_array = @() $ts_server_array += $server1 $ts_server_array += $server2 # do this for each terminal server in the environment foreach ($ts_server in $ts_server_array) { # use qwinsta for oldschool session log off (maximum compatibility) $qwinsta = qwinsta /server:$ts_server | ForEach-Object {$_.Trim() -replace "\s+",","} $activeusersTS = @() foreach ($item in $qwinsta) { if ($item -like "rdp*") { # remove the "rdp-tcp#... if present" $activeusersTS += $item -replace "^(.*?),","" } else { # if there is no "rdp-tcp#..." in the line we're good $activeusersTS += $item } } foreach ($user in $activeusersTS) { if ($user -like "$env:Username*") { # get User line and remove everything left but the Session ID $userid = $user -replace "^(.*?),","" -replace ",.*","" # logoff User rwinsta $userid /server:$ts_server } } }