Last Updated: February 25, 2016
·
2.472K
· ringe

Graceful logoff all users from Windows terminal server

I needed a workaround for logging off users leaving their LibreOffice windows open when they left. They would always meet a recovery dialog in the morning, causing frustration among less skilled users. So I wrote this script and added a schedule to run it.

$timeout = 600
$message = "Save all files! Logging you out in "+ $timeout/60 +" minutes."
$sessions = @()
$cond = "wdica"

# Collect session IDs and warn users
query session | select-string $cond | 
%{$_ -replace " {2,27}"," "} | 
foreach {  $_.ToString().split(" ")[3]} | 
foreach {  $sessions += $_
  msg $_ /TIME:$timeout $message
}

# Wait for timeout
sleep $timeout

# Log off sessions
$sessions | foreach {
  C:\tools\pstools\PsExec.exe -i $_ C:\tools\Nircmd\nircmd.exe win close alltopnodesktop
}

The variables on top can be used to modify the experience. The "$cond" could be a username, for instance.

Downloads

Download the following tools and unzip them into the proper location (used in the script above):