prevent-sleep.ps1 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # PowerShell script to prevent system sleep/hibernate
  2. # This script uses Windows API to prevent system from sleeping
  3. # Run with: powershell -ExecutionPolicy Bypass -File prevent-sleep.ps1
  4. try {
  5. Add-Type @"
  6. using System;
  7. using System.Runtime.InteropServices;
  8. public class PowerManagement {
  9. [DllImport("kernel32.dll")]
  10. public static extern uint SetThreadExecutionState(uint esFlags);
  11. public const uint ES_CONTINUOUS = 0x80000000;
  12. public const uint ES_SYSTEM_REQUIRED = 0x00000001;
  13. public const uint ES_DISPLAY_REQUIRED = 0x00000002;
  14. public const uint ES_AWAYMODE_REQUIRED = 0x00000040;
  15. public static void PreventSleep() {
  16. // Prevent system from sleeping, but allow display to turn off
  17. SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED);
  18. }
  19. public static void AllowSleep() {
  20. // Allow system to sleep normally
  21. SetThreadExecutionState(ES_CONTINUOUS);
  22. }
  23. }
  24. "@
  25. # Prevent sleep
  26. [PowerManagement]::PreventSleep()
  27. # Exit successfully
  28. exit 0
  29. } catch {
  30. # If error occurs, exit with error code
  31. Write-Error $_.Exception.Message
  32. exit 1
  33. }