Skip to content

Instantly share code, notes, and snippets.

@jhenaoz
Last active March 18, 2026 15:57
Show Gist options
  • Select an option

  • Save jhenaoz/85dcbbef8e99f1206309d075b99b807d to your computer and use it in GitHub Desktop.

Select an option

Save jhenaoz/85dcbbef8e99f1206309d075b99b807d to your computer and use it in GitHub Desktop.
Prevent Sleep Windows Script
# PowerShell Script to Prevent Computer Suspend
# This script keeps the computer awake by using Windows API
Write-Host "=======================================" -ForegroundColor Cyan
Write-Host " Computer Suspend Prevention Script " -ForegroundColor Cyan
Write-Host "=======================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "This script will prevent your computer from going to sleep." -ForegroundColor Yellow
Write-Host "Press Ctrl+C to stop the script and allow normal sleep behavior." -ForegroundColor Yellow
Write-Host ""
# Define the SetThreadExecutionState function signature
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
public class PowerManagement
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern uint SetThreadExecutionState(uint esFlags);
public const uint ES_CONTINUOUS = 0x80000000;
public const uint ES_SYSTEM_REQUIRED = 0x00000001;
public const uint ES_DISPLAY_REQUIRED = 0x00000002;
public const uint ES_AWAYMODE_REQUIRED = 0x00000040;
}
'@
try {
# Set the execution state to prevent sleep
# ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED
# This keeps both the system and display awake
$result = [PowerManagement]::SetThreadExecutionState(
[PowerManagement]::ES_CONTINUOUS -bor
[PowerManagement]::ES_SYSTEM_REQUIRED -bor
[PowerManagement]::ES_DISPLAY_REQUIRED
)
if ($result -eq 0) {
Write-Host "Failed to set execution state. Script may not work properly." -ForegroundColor Red
} else {
Write-Host "Suspend prevention activated!" -ForegroundColor Green
Write-Host ""
Write-Host "Computer will stay awake while this script is running..." -ForegroundColor Green
Write-Host ""
# Keep the script running and show a heartbeat every 60 seconds
$counter = 0
while ($true) {
Start-Sleep -Seconds 60
$counter++
$timestamp = Get-Date -Format "HH:mm:ss"
$message = "[$timestamp] Still active... $counter minutes elapsed"
Write-Host $message -ForegroundColor Gray
}
}
}
finally {
# Reset execution state when script is stopped
Write-Host ""
Write-Host "Cleaning up and restoring normal power settings..." -ForegroundColor Yellow
[PowerManagement]::SetThreadExecutionState([PowerManagement]::ES_CONTINUOUS)
Write-Host "Normal sleep behavior restored. You can close this window." -ForegroundColor Green
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment