PowerShell闲置关机脚本PDQ部署失效及功能异常求助
问题解决与脚本修正方案
一、脚本核心问题修正
1. 关机/重启命令错误
本地测试触发重启而非关机,大概率是误用了重启命令。强制关机需使用shutdown.exe /s参数,而非/r(重启),或错误调用Restart-Computer替代Stop-Computer。
2. 修正后的闲置检测+关机脚本
以下是基于Win32 API的正确脚本,解决时间计算和执行逻辑问题:
# 导入Win32 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); } "@ # 计算系统运行时长(毫秒) $bootTime = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime $currentTime = Get-Date $uptimeMs = ($currentTime - $bootTime).TotalMilliseconds # 获取最后一次用户输入的时间戳 $lastInputData = New-Object User32+LASTINPUTINFO $lastInputData.cbSize = [System.Runtime.InteropServices.Marshal]::SizeOf($lastInputData) [User32]::GetLastInputInfo([ref]$lastInputData) | Out-Null $lastInputMs = $lastInputData.dwTime # 计算闲置时长(转换为小时) $idleHours = ($uptimeMs - $lastInputMs) / 3600000 # 检查当前时间是否在21:00-04:00窗口内 $currentHour = (Get-Date).Hour $inSchedule = ($currentHour -ge 21) -or ($currentHour -lt 4) # 满足条件则强制关机 if ($inSchedule -and $idleHours -ge 3) { # /s=关机 /f=强制终止进程 /t 0=立即执行 shutdown.exe /s /f /t 0 }
3. 闲置0分钟触发重启的根因
- 检查脚本是否误写
shutdown.exe /r(重启参数) - 若使用
Stop-Computer,需确认是否因权限或参数缺失导致异常,优先用原生shutdown.exe更稳定
二、PDQ部署无效无报错的解决步骤
1. 权限配置
- 确保PDQ部署账户拥有本地管理员权限,关机操作需要高权限
- 在PDQ部署步骤中勾选「以最高权限运行」
2. 执行上下文调整
- PDQ默认用系统账户(System account)运行,该账户下
GetLastInputInfo获取的是系统级闲置,而非当前登录用户的闲置。若目标机器多用户登录,会导致检测异常 - 解决:在PDQ部署中选择「以登录用户身份运行」,并确保该用户拥有关机权限
3. 日志排查
- 在PDQ控制台「部署历史」中查看目标机器的输出日志,即使无报错也可能有隐性信息
- 在脚本中添加本地日志,便于验证执行情况:
$logPath = "C:\PDQ_Shutdown_Log.txt" "[$(Get-Date)] 当前小时:$currentHour,闲置时长:$idleHours 小时" | Out-File $logPath -Append if ($inSchedule -and $idleHours -ge 3) { "[$(Get-Date)] 执行强制关机" | Out-File $logPath -Append shutdown.exe /s /f /t 0 } else { "[$(Get-Date)] 不满足条件,跳过" | Out-File $logPath -Append } - 部署后查看目标机器的
C:\PDQ_Shutdown_Log.txt,确认脚本是否执行、条件判断是否正确
4. 调度设置验证
- 在PDQ调度中设置「每小时执行」,时间范围限定为21:00至次日04:00,确保仅在指定时段触发
三、测试与优化建议
- 测试时可将
$idleHours -ge 3改为$idleHours -ge 0.01(约36秒),快速验证脚本逻辑 - 若目标机器有域策略限制关机,需先确认域策略允许本地管理员执行关机操作
- 避免PDQ中同时部署冲突脚本,确保关机脚本的调度优先级正确
内容的提问来源于stack exchange,提问作者serlag8622
相关产品推荐
相关产品推荐

