Skip to content

Instantly share code, notes, and snippets.

@jhoneill
Last active February 7, 2025 08:17
Show Gist options
  • Save jhoneill/221503b6e8d68dd00b39103ffbe6f817 to your computer and use it in GitHub Desktop.
Save jhoneill/221503b6e8d68dd00b39103ffbe6f817 to your computer and use it in GitHub Desktop.
# Use Set-thread-execution-state to prevent the computer sleeping. From something of Den Delimarsky's at https://den.dev/blog/caffeinate-windows/
Param ([switch]$Now, [switch]$AndDisplay )
if (-not ('win32.system' -as [type])) {Add-Type -Name System -Namespace Win32 -MemberDefinition @"
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern void SetThreadExecutionState(uint esFlags);
"@}
function Suspend-Sleep {
param ([switch]$AndDisplay)
$ES_DISPLAY_REQUIRED = [uint32]'0x00000002'
$ES_SYSTEM_REQUIRED = [uint32]'0x00000001'
$ES_CONTINUOUS = [uint32]'0x80000000'
if ($AndDisplay) {[win32.system]::SetThreadExecutionState($ES_CONTINUOUS -bor $ES_DISPLAY_REQUIRED)}
else {[win32.system]::SetThreadExecutionState($ES_CONTINUOUS -bor $ES_SYSTEM_REQUIRED )}
}
function Resume-Sleep {[win32.system]::SetThreadExecutionState([uint32]0) }
if ($Now -or $AndDisplay) {Suspend-Sleep -AndDisplay:$AndDisplay}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment