Skip to content

Instantly share code, notes, and snippets.

@AlexDev404
Last active May 22, 2025 06:24
Show Gist options
  • Save AlexDev404/2f6d73fb2061284d621893d6e56481b7 to your computer and use it in GitHub Desktop.
Save AlexDev404/2f6d73fb2061284d621893d6e56481b7 to your computer and use it in GitHub Desktop.
Caffeine - Prevent your Windows computer from falling asleep!
Add-Type @"
using System;
using System.Runtime.InteropServices;
public static class Power
{
[DllImport("kernel32.dll", SetLastError = true)]
public static extern uint SetThreadExecutionState(uint esFlags);
}
"@
# Safely assign flags
$ES_CONTINUOUS = [Convert]::ToUInt32("80000000", 16)
$ES_SYSTEM_REQUIRED = [UInt32]1
$ES_DISPLAY_REQUIRED = [UInt32]2
# Combine the flags
# $flags = $ES_CONTINUOUS -bor $ES_SYSTEM_REQUIRED -bor $ES_DISPLAY_REQUIRED
$flags = $ES_CONTINUOUS -bor $ES_DISPLAY_REQUIRED
Write-Host "🍵 System caffeinated. Press Ctrl+C to stop."
try {
while ($true) {
[Power]::SetThreadExecutionState($flags) | Out-Null
Start-Sleep -Seconds 10
}
} finally {
# Clear flags when script stops
[Power]::SetThreadExecutionState($ES_CONTINUOUS) | Out-Null
Write-Host "✅ Sleep prevention ended."
}
@AlexDev404
Copy link
Author

Credit goes to CHerSun/NoSleep for the original code this was based upon.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment