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="">
          <Actions Context="Author">
              <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>

        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