#requires -RunAsAdministrator
# Specify the number of hours of idle time after which the shutdown should occur.
$idleTimeoutHours = 5
# Specify the task name.
$taskName = 'ShutdownAfterIdling'
# Create the shutdown action.
# Note: Passing -Force to Stop-Computer is the only way to *guarantee* that the
# computer will shut down, but can result in data loss if the user has unsaved data.
$action = New-ScheduledTaskAction -Execute powershell.exe -Argument @"
-NoProfile -Command "Start-Sleep $((New-TimeSpan -Hours $idleTimeoutHours).TotalSeconds); Stop-Computer -Force"
"@
# Specify the user identy for the scheduled task:
# Use NT AUTHORIT\SYSTEM, so that the tasks runs invisibly and
# whether or not users are logged on.
$principal = New-ScheduledTaskPrincipal -UserID 'NT AUTHORITY\SYSTEM' -LogonType ServiceAccount
# Create a settings set that activates the condition to run only when idle.
# Note: This alone is NOT enough - an on-idle *trigger* must be created too.
$settings = New-ScheduledTaskSettingsSet -RunOnlyIfIdle
# New-ScheduledTaskTrigger does NOT support creating on-idle triggers, but you
# can use the relevant CIM class directly, courtesy of this excellent blog post:
# https://www.ctrl.blog/entry/idle-task-scheduler-powershell.html
$trigger = Get-CimClass -ClassName MSFT_TaskIdleTrigger -Namespace Root/Microsoft/Windows/TaskScheduler
# Finally, create and register the task:
Register-ScheduledTask $taskName -Action $action -Principal $principal -Settings $settings -Trigger $trigger -Force
1条答案
按热度按时间oxcyiej71#
任务计划程序不是答案,因为用户可能会超过2小时处于非活动状态。
正如Bitcoin Murderous Maniac在评论中指出的那样:虽然任务计划程序GUI(
taskschedm.msc
)* 表面上 * 将您的最大空闲持续时间限制为2小时,但您实际上 * 可以自由输入更大的值 *(包括单词hours
并按Enter键提交):Duration和WaitTimeout设置已弃用。它们仍然存在于“任务计划程序”用户界面中,它们的接口方法可能仍然返回有效值,但不再使用。
事实上,从Windows 11 22 H2开始,空闲任务的行为似乎仅限于以下,基于我的实验(如果您发现相反的信息,请告诉我们;链接的文档希望仍然准确地描述了计算机被认为(不)空闲时的条件:
然而,你 * 可以 * 建立在这些行为上,以实现你想要的:
Start-Sleep
命令,例如5个小时,然后才打电话给Stop-Computer
。以下是设置此类任务的自包含代码:
NT AUHTORITY\System
的形式运行任务,无论用户是否登录。-Force
必须传递给Stop-Computer
。但请注意,这意味着用户会话中任何未保存的数据都可能丢失。*.ps1
文件)-命令通过-Command
参数传递给powershell.exe
(Windows PowerShell CLI)。