Rexxer

Some tips for me and other

Powershell + Logoff inactive users

We have shared PCs and some people leave their sessions locked. Their audio processes (Skype, players, etc …) still work and it’s the problem.

I wrote the script which runs at a user logon and logoff these inactive users.

function Get-Sessions
{

$queryResults = query session
$starters = New-Object psobject -Property @{“SessionName” = 0; “UserName” = 0; “ID” = 0; “State” = 0; “Type” = 0; “Device” = 0;}
foreach ($result in $queryResults)
{
try
{
if($result.trim().substring(0, $result.trim().indexof(” “)) -eq “SESSIONNAME”)
{
$starters.UserName = $result.indexof(“USERNAME”);
$starters.ID = $result.indexof(“ID”);
$starters.State = $result.indexof(“STATE”);
$starters.Type = $result.indexof(“TYPE”);
$starters.Device = $result.indexof(“DEVICE”);
continue;
}

New-Object psobject -Property @{
“SessionName” = $result.trim().substring(0, $result.trim().indexof(” “)).trim(“>”);
“Username” = $result.Substring($starters.Username, $result.IndexOf(” “, $starters.Username) – $starters.Username);
“ID” = $result.Substring($result.IndexOf(” “, $starters.Username), $starters.ID – $result.IndexOf(” “, $starters.Username) + 2).trim();
“State” = $result.Substring($starters.State, $result.IndexOf(” “, $starters.State)-$starters.State).trim();
“Type” = $result.Substring($starters.Type, $starters.Device – $starters.Type).trim();
“Device” = $result.Substring($starters.Device).trim()
}
}
catch
{
$e = $_;
#Write-Log “ERROR: on $srv” + $e.PSMessageDetails
}
}
}
New-EventLog -LogName Application -Source “SessionDisconnector”
$queryResults = Get-Sessions | Where-object State -eq Disc
If ($queryResults -ne $NULL) {
ForEach ($queryResult in $queryResults) {
If ($queryResult.Username -ne “”) {
write-host Found a disconnected user: $queryResult.Username
write-EventLog -LogName Application -Source “SessionDisconnector” -EntryType Information -EventID 1 -Message “Found a disconnected user: $queryResult.Username”
write-host Logging off disconnected users …
logoff $queryResult.ID
}
}
}

Comments are currently closed.