Thursday, 13 October 2016

Automatically logoff sessions from windows server using Powershell

Windows server has the functionality through group policy to automatically log off users at a certain time of day, or once their set logon hours expire etc, but in my experience (and many other users based on internet research), it doesn't work very reliably.

Here is a script you  can use that will get a list of all current user sessions on a server, and log them off. A "safelist" is also included where you can specify usernames that should not be logged off automatically by this script - ie. administrator accounts etc. Usernames should be specified in inverted commas and separated by single commas.

I've also incorporated logging functionality, as it may be useful to know what users are staying logged onto the server (perhaps when they shouldn't be), and to be 100% certain about what the script is doing, or has done. Adjust the $logfile variable as required, or ensure the default folder (C:\Admin) exists for it to work correctly.

This does not require any additional modules to be installed either.

The script works by using the query session command, and then manipulating/formatting the results to obtain a list of current user sessions. Because the query session command is a DOS based command, the results aren't formatted nicely into variables/members that powershell can easily understand and work with, so formatting/manipulation is done using the .Substring and .Trim functions. The list of user sessions t hat is obtained is then compared against the safelist and if the user is not present in the safelist, is then logged off the server.

You will need to setup a scheduled task to run this powershell script - you can view my blog post here on setting up Powershell scripts to run via scheduled tasks in windows

$safelist = "administrator", "user1"
$date = get-date -f "ddMMyyyy"
$logfile = "C:\Admin\LogOffScript-$date.txt"

$sessions = query session |  where-object { $_ -notmatch '^ SESSIONNAME' } | %{
    $item = "" | Select "Active", "SessionName", "Username", "Id", "State", "Type", "Device"
    $item.Active = $_.Substring(0,1) -match '>'
    $item.SessionName = $_.Substring(1,18).Trim()
    $item.Username = $_.Substring(19,20).Trim()
    $item.Id = $_.Substring(39,9).Trim()
    $item.State = $_.Substring(48,8).Trim()
    $item.Type = $_.Substring(56,12).Trim()
    $item.Device = $_.Substring(68).Trim()

foreach ($session in $sessions)
if ($safelist -notcontains $($session.username))
$time = get-date
logoff $($
write-output "$time | Logged off $($session.username)" | out-file $logfile -append

No comments:

Post a comment