如果用户在 PowerShell 中处于非活动状态一段时间,则关闭 PC 的脚本

问题描述 投票:0回答:1

如果用户不活动则自动关闭。

我正在尝试创建一个一次性 powershell 脚本,以便在用户一段时间内不活动时关闭电脑。

我环顾四周,但解决我问题的唯一答案是使用 VB。任务计划程序不是答案,因为用户可能处于非活动状态超过 2 小时。

powershell scheduled-tasks windows-task-scheduler idle-timer idle-processing
1个回答
1
投票

任务计划程序不是答案,因为用户可能处于非活动状态超过 2 小时。

正如 Bitcoin Murderous Maniac 在评论中指出的那样:虽然任务计划程序 GUI (

taskschedm.msc
) 看似将您的最大空闲持续时间限制为 2 小时,但实际上您可以自由输入更大的值 (包含单词
hours
并使用 Enter 提交):

不幸的是,此空闲超时不再支持(来自文档):

Duration 和 WaitTimeout 设置已弃用。它们仍然存在于任务计划程序用户界面中,并且它们的接口方法可能仍然返回有效值,但不再使用它们。

事实上,从 Windows 11 22H2 开始,根据我的实验,空闲任务的行为似乎仅限于以下(如果您发现相反的信息,请告诉我们;希望链接的文档仍能准确描述计算机被视为(不)空闲的条件):

  • 检测到空闲条件时立即启动任务(最早在硬编码 4 分钟后发生)。

  • 当计算机停止空闲时,启动的任务会立即终止 - 也就是说,任务计划程序 GUI 中看似允许任务继续运行的复选框不再有效。

  • 当计算机再次空闲时,任务总是重新启动 - 也就是说,任务计划程序 GUI 中看似允许任务在先前终止后“不”重新启动的复选框不再有效。

但是,

可以以这些行为为基础来实现你想要的

    当任务在进入空闲状态时启动,首先启动
  • Start-Sleep

     命令等待所需的持续时间,例如5个小时,然后
    然后打电话给Stop-Computer

  • 如果计算机立即处于空闲状态那么长时间,关机将按计划进行。
  • 如果计算机在此之前退出空闲状态,您的任务将终止,这样就不会发生过早关闭的情况 - 然后在下次进入空闲状态时重新启动。
以下是
设置此类任务的独立代码

    它以
  • NT AUHTORITY\System

    的方式运行任务,不可见,无论用户是否登录。

    
    

    为了使用此用户身份设置任务,您需要在
      elevated
    • 会话中运行代码(以管理员身份运行)。
  • 保证

    关闭不仅启动而且完成的唯一方法,-Force必须传递给

    Stop-Computer
    。但请注意,这意味着用户会话中任何未保存的数据都可能会丢失。
    
    

  • 无需 PowerShell
  • 脚本

    *.ps1 文件) - 命令通过其

    powershell.exe
    参数传递到 Windows PowerShell CLI
    -Command
    
    

  • 请参阅源代码中的注释以获取更多信息。
  • #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
© www.soinside.com 2019 - 2024. All rights reserved.