求PowerShell脚本:检测Windows系统空闲时长满90分钟自动重启
PowerShell脚本:检测系统空闲时长并自动重启
以下是满足需求的PowerShell脚本,它会持续监测系统空闲状态,当空闲时间达到90分钟及以上时自动重启计算机:
# 定义获取系统空闲时间所需的API结构体和函数 Add-Type @" using System; using System.Runtime.InteropServices; public class User32 { [StructLayout(LayoutKind.Sequential)] public struct LASTINPUTINFO { public uint cbSize; public uint dwTime; } [DllImport("user32.dll")] public static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); } "@ # 设置空闲阈值(90分钟转换为毫秒) $idleThreshold = 90 * 60 * 1000 while ($true) { # 获取当前系统运行时间(毫秒) $systemUptime = [Environment]::TickCount # 初始化LASTINPUTINFO结构体 $lastInputInfo = New-Object User32+LASTINPUTINFO $lastInputInfo.cbSize = [System.Runtime.InteropServices.Marshal]::SizeOf($lastInputInfo) # 获取最后一次输入的时间戳 [User32]::GetLastInputInfo([ref]$lastInputInfo) | Out-Null $idleTime = $systemUptime - $lastInputInfo.dwTime # 检查是否达到空闲阈值 if ($idleTime -ge $idleThreshold) { Write-Host "系统已空闲超过90分钟,即将重启..." # 执行重启操作,-Force参数强制关闭未保存的程序(可选,根据需求调整) Restart-Computer -Force break } # 每30秒检测一次,可根据需要调整间隔 Start-Sleep -Seconds 30 }
关键说明:
- 脚本通过调用Windows API
GetLastInputInfo获取用户最后一次输入的时间,计算与当前系统运行时间的差值得到空闲时长 $idleThreshold变量设置为90分钟对应的毫秒数,可根据需求修改- 循环每隔30秒检测一次空闲状态,检测间隔可通过调整
Start-Sleep的参数修改 Restart-Computer -Force会强制重启,若需要给用户提示或等待程序关闭,可移除-Force参数,或添加-Delay参数设置延迟重启时间
使用注意:
- 脚本需要以管理员权限运行,否则
Restart-Computer命令可能无法执行 - 测试时可先将
$idleThreshold设为较小值(比如30秒)验证功能正常,再改回90分钟
内容的提问来源于stack exchange,提问作者Darren
相关产品推荐
相关产品推荐

