Auto Shutdown if user is inactive.
I am trying to create a one time powershell script to shut down the pc if the user is inactive for a period of time.
I have done some looking around but the only answer to my problem was using VB. The task scheduler is not the answer as the users might be inactive for more than 2 hours.
As Bitcoin Murderous Maniac points out in a comment: While the Task Scheduler GUI (
taskschedm.msc) seemingly limits you to a maximum idle duration period of 2 hours, you're actually free to type in larger values (include the wordhoursand submit with Enter):Unfortunately, however this idle timeout is no longer supported (from the docs):
De facto, as of Windows 11 22H2, the behavior of on-idle tasks appears to be limited to the following, based on my experiments (do tell us if you find information to the contrary; the linked docs hopefully still accurately describe the conditions when a computer is considerd (not) idle):
The task is launched instantly when an idle condition is detected (which happens after a hard-coded 4 minutes at the earliest).
When the computer stops being idle, the launched task is instantly terminated - that is, the check box in the Task Scheduler GUI that seemingly allows the task to continue to run is no longer effective.
When the computer becomes idle again, the task is invariably restarted - that is, the check box in the Task Scheduler GUI that seemingly allows the task not to restart after having previously been terminated is no longer effective.
However, you can build on these behaviors to achieve what you want:
When the task is launched on entering the idle state, first launch a
Start-Sleepcommand that waits for the desired duration, e.g. 5 hours, and only then callStop-Computer.If the computer stays idle for that long right away, the shutdown will occur as planned.
If the computer exits the idle state before that, your task is terminated, so that no premature shutdown occurs - and then restarted the next time the idle state is entered.
The following is self-contained code that sets up such a task:
It runs the task as
NT AUHTORITY\System, invisibly, and irrespective of whether a user is logged on or not.The only way to guarantee that a shutdown is not just initiated but completes,
-Forcemust be passed toStop-Computer. Note, however, that this means that any unsaved data in a user's session may be lost.No PowerShell script (
*.ps1file) is necessary - the commands are passed topowershell.exe, the Windows PowerShell CLI, via its-Commandparameter.See the comments in the source code for additional information.