4

As background for this question: we have a Windows Server 2012 R2 Terminal Server where users do long-running work, so we try very hard not to reboot the server unneccessarily. However, sometimes we need to (installing updates being the most important), and this currently requires a lot of communication and manual interference.

This would be implified a lot if the reboot could happen automatically when the server is not in active use. So far my best attempt involved a scheduled task triggered on the event Security/Security Auditing/4634 (Logoff), but I failed to then determine if the just disconnected session was the last session, and that may not be the best approach anyway.

Is there a way to perform a task (i.e. PS Restart-Computer) as soon as there are no active sessions (interactive or disconnected)?

Martok
  • 43
  • 4

1 Answers1

2

Something like this may work. Run it as a one-time scheduled task with identity system when you need to restart.

SET LOGFILE=C:\TEMP\Reboot.log
ECHO. (*)    %DATE% %TIME% > %LOGFILE%
:CHECKSESSIONS
ECHO. (*)    %DATE% %TIME% Waiting one minute... >> %LOGFILE%
REM WAIT ONE MINUTE
TIMEOUT /T 60
QUERY USER >> %LOGFILE% 2>&1
FOR /F "tokens=*" %%i IN ('QUERY USER ^| FIND /C "Active"') DO SET ACTIVESESSIONS=%%i >> %LOGFILE% 2>&1
IF %ACTIVESESSIONS% GTR 0 (
    ECHO Active sessions: %ACTIVESESSIONS% >> %LOGFILE% 2>&1
    GOTO :CHECKSESSIONS
)
FOR /F "tokens=*" %%i IN ('QUERY USER ^| FIND /C "Disc"') DO SET DISCONNECTEDSESSIONS=%%i >> %LOGFILE% 2>&1
IF %DISCONNECTEDSESSIONS% GTR 0 (
    ECHO Disconnected sessions: %DISCONNECTEDSESSIONS% >> %LOGFILE% 2>&1
    GOTO :CHECKSESSIONS
)

ECHO. (*)    %DATE% %TIME% Restarting computer >> %LOGFILE%
SHUTDOWN /F /R /T 0 >> %LOGFILE% 2>&1
Greg Askew
  • 35,880
  • 5
  • 54
  • 82
  • Thanks! I was hoping to be able to avoid polling, but that would to the trick. – Martok May 13 '17 at 13:15
  • Going ahead and accepting this as the answer, as it's essentially what I ended up doing (in PS). I replaced the loop with a scheduled task that checks every 5 minutes (as that's easier to abort than a process on the system winsta), and used `PSTerminalServices` to query sessions and send them announcements (and probably overengineered the entire thing). Other than that, same concept. – Martok May 22 '17 at 14:18