• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1348
  • Last Modified:

batch script to check if anyone is logged in to terminal server and then reboot?

I have a .bat file with a simple "shutdown -r" that is run every night at 04:00.
However I wish to change the script so that it checks if anyone is logged in first.
If no users are logged in then continue with the reboot.
If 1 or more users are logged in then it should not reboot.
  • 2
1 Solution
Assuming this is exclusively for servers (not XP): you can look for active or disconnected sessions; if none exist, do the reboot.
As usual, try it on a test server first
Terminal Server Commands: QUERY

query session | findstr /i "Active Disc."
if errorlevel 1 shutdown -r

Open in new window

bergsprekkenAuthor Commented:
It works, had to remove the "." in "Active Disc." though.

query session | findstr /i "Active Disc"
if errorlevel 1 echo Nobody logged in :o
if errorlevel 0 echo Dont reboot - people are working..
Sorry for the ".", had to take this out of the document above.
And you don't need the last line; "if errorlevel 0" is *always* true. "if errorlevel X" checks if the errorlevel is X *or* *higher*.
To check for no error, you'd need "if not errorlevel 1", or you can use if ... else, for example like this:

query session | findstr /i "Active Disc."
if errorlevel 1 (
  Rebooting in 1 minute, enter 'shutdown -a' to abort ...
  shutdown -r -t 60
) else (
  Don't reboot - people are working.

Open in new window


Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now