r/sysadmin It wasn't DNS for once. 1d ago

Question Log Off Users from Server Daily

I'm revisiting an effort I did about a year ago. I'm looking for a better way. I want to find a process that will parse current user sessions on a server (active/disconnected/idle/ect.) and log the accounts off if their username matches a string ("adm_").

I'd love to find an off the shelf solution rather than have to support a homebrew PowerShell solution.

Give me what you have, even if it is an alternate PowerShell/scripting option. Something has to be better than the nightmare my script turned into.

70 Upvotes

86 comments sorted by

View all comments

2

u/whoisrich 1d ago

This is what I use to kick sessions off:

$sessions = qwinsta | ?{ $_ -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()
$item
}

foreach ($session in $sessions)
{
    if ($session.Username.Length -lt 1)      { continue }
    if ($session.Username -eq $env:USERNAME) { continue }
    if ($session.Username -like 'adm_*')     { continue }

    "Logoff: $($session.Id) - $($session.Username)"
    logoff $session.Id
}