KeepAwake.ps1# KeepAwake.ps1# 防止屏幕自动关闭并阻止系统自动睡眠# 仅在类型尚未加载时定义避免重复运行时报错if(-not([System.Management.Automation.PSTypeName]SleepPrevent).Type){Add-Type using System; using System.Runtime.InteropServices; public class SleepPrevent { [DllImport(kernel32.dll, SetLastError true)] public static extern uint SetThreadExecutionState(uint esFlags); } }# Windows 电源管理标志$ES_CONTINUOUS[uint32]2147483648$ES_SYSTEM_REQUIRED[uint32]1$ES_DISPLAY_REQUIRED[uint32]2# 保持系统运行同时保持屏幕开启$flags$ES_CONTINUOUS-bor$ES_SYSTEM_REQUIRED-bor$ES_DISPLAY_REQUIRED# 启用屏幕常亮$result[SleepPrevent]::SetThreadExecutionState($flags)if($result-eq0){$errorCode[Runtime.InteropServices.Marshal]::GetLastWin32Error()Write-Host❌ 设置失败Windows 错误代码$errorCode-ForegroundColor Redexit1}Write-Host✅ 屏幕常亮已开启-ForegroundColor GreenWrite-Host✅ 系统自动睡眠已阻止-ForegroundColor GreenWrite-Host按 CtrlC 退出退出后恢复正常电源管理。-ForegroundColor Yellowtry{while($true){Start-Sleep-Seconds 1}}finally{# 恢复 Windows 默认的执行状态管理[void][SleepPrevent]::SetThreadExecutionState($ES_CONTINUOUS)Write-Hostn 已恢复正常电源管理。-ForegroundColor Cyan}