Friday, June 19, 2015

Windows scheduled task to auto logoff

Here's some PowerShell to remotely schedule a task to log out 2+ hours idle users:
function InstallAutoLogoff($computer)
{
    invoke-command -computer $computer `
    {
        schtasks.exe /delete /tn AutoLogOff /f 2>&1 | Out-Null

        set-content c:\windows\temp\AutoLogOffTask.xml `
        '<?xml version="1.0" encoding="UTF-16"?>
        <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
          <Triggers>
            <TimeTrigger>
              <Repetition>
                <Interval>PT30M</Interval>
              </Repetition>
              <StartBoundary>2015-01-01T00:00:00</StartBoundary>
            </TimeTrigger>
          </Triggers>
          <Actions Context="Author">
            <Exec>
              <Command>PowerShell.exe</Command>
              <Arguments>-Command $r1 = quser.exe; $idPos = $r1[0].IndexOf(''ID  ''); foreach($row in $r1) { $r2 = $row.Substring($idPos).Trim() -split ''  +''; if($r2[2].Contains('':'')) { $t = $r2[2].Replace('':'', ''.''); if($t.Contains(''+'') -or ($t -as [double] -ge 2)) { rwinsta.exe $r2[0] } } }</Arguments>
            </Exec>
          </Actions>
        </Task>'

        schtasks.exe /create /tn AutoLogOff /ru system /xml c:\windows\temp\AutoLogOffTask.xml
        del c:\windows\temp\AutoLogOffTask.xml
    }
}

InstallAutoLogoff 'myserver1'
InstallAutoLogoff 'myserver2'
InstallAutoLogoff 'myserver3'

No comments:

Post a Comment