-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnosleep.ps1
More file actions
60 lines (49 loc) · 1.72 KB
/
nosleep.ps1
File metadata and controls
60 lines (49 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
$log = "$env:USERPROFILE\Desktop\nosleep.log"
function Write-Log($msg) {
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
"$timestamp - $msg" | Out-File -Append -FilePath $log
}
try {
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class Power {
[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr PowerCreateRequest(ref REASON_CONTEXT context);
[DllImport("kernel32.dll")]
public static extern bool PowerSetRequest(IntPtr handle, int requestType);
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr handle);
public const int PowerRequestExecutionRequired = 0;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct REASON_CONTEXT {
public uint Version;
public uint Flags;
[MarshalAs(UnmanagedType.LPWStr)]
public string ReasonString;
}
}
"@ -ErrorAction Stop
$ctx = New-Object Power+REASON_CONTEXT
$ctx.Version = 0
$ctx.Flags = 1
$ctx.ReasonString = "Prevent system sleep"
$request = [Power]::PowerCreateRequest([ref]$ctx)
$setResult = [Power]::PowerSetRequest($request, [Power]::PowerRequestExecutionRequired)
if ($setResult) {
Write-Log "nosleep.ps1 started successfully — power request set"
} else {
Write-Log "ERROR: PowerSetRequest failed"
}
} catch {
Write-Log "ERROR: Failed to load PowerRequest code — $($_.Exception.Message)"
exit 1
}
while ($true) {
Write-Log "Preventing sleep (active)"
$lines = Get-Content -Path $log -ErrorAction SilentlyContinue
if ($lines.Count -gt 10000) {
$lines[-10000..-1] | Set-Content -Path $log
}
Start-Sleep -Seconds 60
}