Last active
February 18, 2026 19:58
-
-
Save santisq/6898fcdab5af97fab0c8c03881b72260 to your computer and use it in GitHub Desktop.
SetThreadExecutionState... keeps your powershell script running without going to sleep
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.ComponentModel; | |
| using System.Runtime.InteropServices; | |
| public static class Native | |
| { | |
| public static EXECUTION_STATE? PreviousState { get; private set; } | |
| [DllImport("kernel32.dll", SetLastError = true, EntryPoint = "SetThreadExecutionState")] | |
| private static extern EXECUTION_STATE SetThreadExecutionStateNative(EXECUTION_STATE esFlags); | |
| public static void SetThreadExecutionState(EXECUTION_STATE esFlags) | |
| { | |
| if (esFlags.HasFlag(EXECUTION_STATE.ES_AWAYMODE_REQUIRED) | |
| && !esFlags.HasFlag(EXECUTION_STATE.ES_CONTINUOUS)) | |
| { | |
| throw new ArgumentException("ES_AWAYMODE_REQUIRED must be used with ES_CONTINUOUS."); | |
| } | |
| EXECUTION_STATE previousState = SetThreadExecutionStateNative(esFlags); | |
| if (previousState == 0) throw new Win32Exception(); | |
| PreviousState = previousState; | |
| } | |
| public static void Restore() => SetThreadExecutionState(PreviousState ?? EXECUTION_STATE.ES_CONTINUOUS); | |
| } | |
| [Flags] | |
| public enum EXECUTION_STATE : uint | |
| { | |
| ES_AWAYMODE_REQUIRED = 0x00000040, | |
| ES_CONTINUOUS = 0x80000000, | |
| ES_DISPLAY_REQUIRED = 0x00000002, | |
| ES_SYSTEM_REQUIRED = 0x00000001 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment