Last active
October 28, 2024 18:19
-
-
Save jcefoli/66dd9e0cdf865a43175d0d48d272b25a to your computer and use it in GitHub Desktop.
Powershell Computer Keepalive (Anti-Idle)
This file contains 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
<# | |
This script will prevent GPOs from enabling the screensaver, shutting off your screen, or force-locking your workstation | |
It works by sending an F15 keystroke every minute (only if there have been no keystrokes or mouse movement for 30 seconds) | |
Be green - if you want to use this, power off your monitor(s)! | |
#> | |
Add-Type @' | |
using System; | |
using System.Diagnostics; | |
using System.Runtime.InteropServices; | |
namespace PInvoke.Win32 { | |
public static class UserInput { | |
[DllImport("user32.dll", SetLastError=false)] | |
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); | |
[StructLayout(LayoutKind.Sequential)] | |
private struct LASTINPUTINFO { | |
public uint cbSize; | |
public int dwTime; | |
} | |
public static DateTime LastInput { | |
get { | |
DateTime bootTime = DateTime.UtcNow.AddMilliseconds(-Environment.TickCount); | |
DateTime lastInput = bootTime.AddMilliseconds(LastInputTicks); | |
return lastInput; | |
} | |
} | |
public static TimeSpan IdleTime { | |
get { | |
return DateTime.UtcNow.Subtract(LastInput); | |
} | |
} | |
public static int LastInputTicks { | |
get { | |
LASTINPUTINFO lii = new LASTINPUTINFO(); | |
lii.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO)); | |
GetLastInputInfo(ref lii); | |
return lii.dwTime; | |
} | |
} | |
} | |
} | |
'@ # https://stackoverflow.com/questions/39312540/how-to-detect-user-activity-input-or-lack-thereof-on-a-pc | |
$host.ui.RawUI.WindowTitle = "Idle Keepalive" | |
$myshell = New-Object -com "Wscript.Shell" | |
While($true) { | |
$i++ | |
Start-Sleep -Seconds 60 | |
#Calculate idle time | |
$idleTime = [PInvoke.Win32.UserInput]::IdleTime | |
$TimeSpan = New-TimeSpan -Seconds 30 | |
#Only send keystroke if Windows API reports idle for more than 30 seconds. This should limit sending keystrokes when not idle, in case they mess up apps | |
if ($idleTime -gt $TimeSpan) { | |
$myshell.sendkeys("{SCROLLLOCK}") | |
Start-Sleep -Milliseconds 100 | |
$myshell.sendkeys("{SCROLLLOCK}") | |
Write-Output "Keepalive script has been running for $i minutes [F15 key sent]" | |
}else { | |
Write-Output "Keepalive script has been running for $i minutes" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment