Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Logoff inactive user sessions after 2 days
# Version 1
$idleDays = 2
$users = (((query user) -replace '^>', '') -replace '\s{2,}', ',').Trim() |
ForEach-Object {
if ($_.Split(',').Count -eq 5) {
Write-Output ($_ -replace '(^[^,]+)', '$1,')
}
else {
Write-Output $_
}
} | ConvertFrom-Csv
foreach ($user in ($users | Where-Object { $_.STATE -match 'Disc' })) {
if ($user.'IDLE TIME' -contains '+' -and
[int]$user.'IDLE TIME'.split('+')[0] -ge $idleDays) {
Write-Output 'Logging off inactive user' $user.USERNAME
logoff $user.ID
}
}
# V1 again. Just under the 255 character task scheduler command length limit with 'powershell -c'.
(((quser)-replace'^>','')-replace'\s{2,}',',').Trim()|%{if($_.Split(',').Count-eq5){$_-replace'(^[^,]+)','$1,'}else{$_}}|ConvertFrom-Csv|?{$_.STATE-match'Disc'}|%{if($_.'IDLE TIME'-contains'+'-and[int]$_.'IDLE TIME'.split('+')[0]-ge2){logoff $_.ID}}
# Versions 2
$idleDays = 2
function Get-QUsers() {
foreach ($line in ((query user | Select-Object -Skip 1) -replace '\s{2,}', ',')) {
if ($line.Split(',').Count -eq 5) {
$line = $line.Insert($line.IndexOf(','), ',')
}
$user, $session, $id, $state, $idleTime, $logonTime = $line.split(',')
$idleTime = if ($idleTime -match '\+') {
$idleTime.replace('+', '.')
} elseif ($idleTime -match '\d') {
'0:' + $idleTime
} else { 0 }
[PSCustomObject]@{
PSTypeName = 'QuserObject'
UserName = $user.replace('>', '').trim()
Session = $session
ID = [int]$id
State = $state
IdleTime = [timespan]$idleTime
LogonTime = [datetime]$logonTime
IsCurrent = $user.StartsWith('>')
}
}
}
foreach ($user in (Get-QUsers)) {
if ($user.State -match 'Disc' -and $user.IdleTime.Days -ge $idleDays) {
Write-Output 'Logging off inactive user' $user.UserName
logoff $user.ID
}
}
# Version 3
$idleDays = 2
$maxDays = 5
class QuserObject {
[string] $UserName
[string] $Session
[int] $ID
[string] $State
[timespan] $IdleTime
[datetime] $LogonTime
[bool] hidden $IsCurrent
QuserObject () {}
[datetime] GetIdleDate() {
return [datetime]::Now - $this.IdleTime
}
}
function Get-QUsers() {
foreach ($line in ((query user | Select-Object -Skip 1) -replace '\s{2,}', ',')) {
[System.Collections.ArrayList]$fields = $line.split(',')
if ($fields.Count -eq 5) { $fields.Insert(1, '') }
$fields[4] = (($fields[4].Replace('+', '.') -replace '^(\d+)$', '0:$1') -replace '^[^:]+$', '0')
[QuserObject]@{
UserName = $fields[0].replace('>', '').trim()
Session = $fields[1]
ID = [int]$fields[2]
State = $fields[3]
IdleTime = [timespan]$fields[4]
LogonTime = [datetime]$fields[5]
IsCurrent = $fields[0].StartsWith('>')
}
}
}
foreach ($user in (Get-QUsers)) {
if (($user.State -match 'Disc' -and $user.IdleTime.Days -ge $idleDays) -or
((Get-Date) - $user.LogonTime).Days -ge $maxDays) {
Write-Output 'Logging off inactive user' $user.UserName
logoff $user.ID
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment