LLI Wiki — My Digital Knowledge Base

PowerShell: prevent the session from sleeping or locking

PowerShell scripts that simulate a key press or a mouse movement at regular intervals to prevent sleep or screen locking.

These PowerShell scripts simulate keyboard or mouse activity to prevent the session from going to sleep or locking. They use the Wscript.Shell COM object and System.Windows.Forms.

Send the Scroll Lock key at regular intervals

$WShell = New-Object -Com "Wscript.Shell"
while (1) {$WShell.SendKeys("{SCROLLLOCK}"); sleep 60}

Send a character for a set duration

The script sends a dot every minute for the given number of minutes (60 by default):

param($minutes = 60)
$myshell = New-Object -com "Wscript.Shell"
for ($i = 0; $i -lt $minutes; $i++) {
    Start-Sleep -Seconds 60
    $myshell.sendkeys(".")
}

Move the mouse cursor

The cursor is moved one pixel down and to the right every 5 seconds:

Add-Type -AssemblyName System.Windows.Forms
while ($true) {
    $Pos = [System.Windows.Forms.Cursor]::Position
    $x = ($pos.X) + 1
    $y = ($pos.Y) + 1
    [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y)
    Start-Sleep -Seconds 5
}

Combine the key press and the mouse movement

$WShell = New-Object -Com "Wscript.Shell"
$myshell = New-Object -com "Wscript.Shell"
Add-Type -AssemblyName System.Windows.Forms

while (1) {
    $WShell.SendKeys("{SCROLLLOCK}"); 
    $Pos = [System.Windows.Forms.Cursor]::Position
    $x = ($pos.X) + 1
    $y = ($pos.Y) + 1
    [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y) 
    write-host $x
    sleep 20
    write-host "keepalive ."
    $myshell.sendkeys(".")
    
    }

Notes

Mastodon LLIMastodon SocialFosstodon