You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写PowerShell脚本实现用户闲置一段时间后自动关机

一次性PowerShell脚本:闲置超时自动关机

以下是直接可用的PowerShell脚本,无需依赖VB脚本或任务计划程序,可实时检测用户闲置时长,达到设定阈值后自动关机:

# 设置闲置阈值(单位:秒,示例为2小时=7200秒)
$idleThreshold = 7200

# 导入Windows API用于获取用户最后输入时间
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class UserInput {
    [StructLayout(LayoutKind.Sequential)]
    public struct LASTINPUTINFO {
        public uint cbSize;
        public uint dwTime;
    }
    [DllImport("user32.dll")]
    public static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
}
"@

# 初始化LASTINPUTINFO结构体
$lastInputInfo = New-Object UserInput+LASTINPUTINFO
$lastInputInfo.cbSize = [System.Runtime.InteropServices.Marshal]::SizeOf($lastInputInfo)

Write-Host "脚本已启动,将在用户闲置超过$($idleThreshold/3600)小时后自动关机..."
Write-Host "按Ctrl+C可终止脚本"

while ($true) {
    # 获取最后输入时间
    [UserInput]::GetLastInputInfo([ref]$lastInputInfo) | Out-Null
    # 获取当前系统运行时间(毫秒)
    $currentTick = [System.Environment]::TickCount
    # 计算闲置时长(秒)
    $idleTime = ($currentTick - $lastInputInfo.dwTime) / 1000

    # 检查是否达到闲置阈值
    if ($idleTime -ge $idleThreshold) {
        Write-Host "检测到用户已闲置超过$($idleThreshold/3600)小时,即将关机..."
        # 执行关机命令,/t 0表示立即关机,可改为/t 60延迟60秒关机
        shutdown /s /t 0
        exit
    }

    # 每隔60秒检测一次,减少资源占用
    Start-Sleep -Seconds 60
}

脚本说明

  • 闲置阈值调整:修改$idleThreshold的值即可自定义闲置时长,比如设置为3600表示1小时,14400表示4小时。
  • API调用逻辑:通过调用user32.dll的GetLastInputInfo函数,直接获取系统记录的用户最后一次输入(鼠标/键盘操作)的时间戳,结合当前系统运行时间计算闲置时长,精度可靠。
  • 资源占用优化:每次检测间隔60秒,避免高频循环消耗系统资源,可根据需求调整Start-Sleep的秒数。
  • 关机选项:shutdown /s /t 0为立即关机,若需要在关机前给用户提示,可改为shutdown /s /t 60 /c "电脑将在60秒后关机,因检测到长时间闲置",添加提示信息和延迟。

使用方法

  1. 将上述代码复制到文本编辑器,保存为IdleShutdown.ps1。
  2. 右键以管理员身份运行PowerShell,执行该脚本(若遇到执行策略限制,可先运行Set-ExecutionPolicy RemoteSigned -Scope CurrentUser临时调整策略)。
  3. 脚本运行后会在控制台显示状态,按Ctrl+C可随时终止脚本。

内容的提问来源于stack exchange,提问作者eruannaa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 03:52:42