sizz sizz - 1 year ago 117
Powershell Question

Log Off multiple Idle users

$idle_timout = New-TimeSpan -minutes 1
Add-Type @'
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace PInvoke.Win32 {

public static class UserInput {

[DllImport("user32.dll", SetLastError=false)]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

private struct LASTINPUTINFO {
public uint cbSize;
public int dwTime;

public static DateTime LastInput {
get {
DateTime bootTime = DateTime.UtcNow.AddMilliseconds(-Environment.TickCount);
DateTime lastInput = bootTime.AddMilliseconds(LastInputTicks);
return lastInput;

public static TimeSpan IdleTime {
get {
return DateTime.UtcNow.Subtract(LastInput);

public static int LastInputTicks {
get {
lii.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO));
GetLastInputInfo(ref lii);
return lii.dwTime;

$userId = (Get-Process -PID $pid).SessionID
echo $userID
$loggedOff = 0

foreach ($user in $userid){
$idle_time = [PInvoke.Win32.UserInput]::IdleTime

if (($loggedOff -eq 0) -And ($idle_time -gt $idle_timout))
logoff $user

$loggedOff = 1

if ($idle_time -lt $idle_timout)
$loggedOff = 0
while (1 -eq 1)


Hey guys I was wondering if anyone could help me with this script. What i am trying to do its log off all users in our conference rooms after a given idle time. What I am trying to do is find all session id's and log off all active sessions. I am not worried about losing work as these are conference room computers. the problem I have is that i can get the session id for the current logged in user but not for all the users logged in. If anyone has any insight it would be greatly appreciated.

Answer Source

here are some options that may be of use

powershell way

$computer = 'localhost'
$owners = @{}
Get-WmiObject win32_process -ComputerName $computer -Filter 'name = "explorer.exe"' | % {$owners[$_.handle] = $_.getowner().user}
Get-Process -ComputerName $computer explorer | % {$owners[$]}

or these

$server = 'localhost'

(quser /server:$server) -replace '\s{2,}', ',' | ConvertFrom-Csv

query session /server:$server
qwinsta /server:$server

query user /server:$server
quser /server:$server

qprocess explorer.exe /server:$server