Skip to content

Instantly share code, notes, and snippets.

@AliYusuf95
Created September 5, 2022 08:17
Show Gist options
  • Save AliYusuf95/90b4c1f6c2d3fbdb061d052a1ffb6798 to your computer and use it in GitHub Desktop.
Save AliYusuf95/90b4c1f6c2d3fbdb061d052a1ffb6798 to your computer and use it in GitHub Desktop.
Prevent PC from sleep PowerShell script
Add-Type -AssemblyName System.Windows.Forms
# Add-Type -Name ConsoleUtils -Namespace WPIA -MemberDefinition @'
# [DllImport("Kernel32.dll")]
# public static extern IntPtr GetConsoleWindow();
# [DllImport("user32.dll")]
# public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
# '@
# # Hide Powershell window
# $hWnd = [WPIA.ConsoleUtils]::GetConsoleWindow()
# [WPIA.ConsoleUtils]::ShowWindow($hWnd, 0)
param($sleep = 60) # Seconds
Clear-Host
$announcementInterval = 10 # loops
$plusOrMinus = 1 # Mouse position increment or decrement
$WShell = New-Object -com "Wscript.Shell"
$date = Get-Date -Format "dddd MM/dd HH:mm (K)"
$stopwatch
# Some environments don't support invocation of this method.
try {
$stopwatch = [system.diagnostics.stopwatch]::StartNew()
} catch {
Write-Host "Couldn't start the stopwatch."
}
Write-Host "Executing NoSleep routine."
Write-Host "Start time:" $(Get-Date -Format "dddd MM/dd HH:mm (K)")
$index = 0
while ($true)
{
# heartbeat
Write-Host "<3" -fore red
# Press ScrollLock key
$WShell.sendkeys("{SCROLLLOCK}")
Start-Sleep -Milliseconds 200
$WShell.sendkeys("{SCROLLLOCK}")
# Move mouse
$p = [System.Windows.Forms.Cursor]::Position
$x = $p.X + $plusOrMinus
$y = $p.Y + $plusOrMinus
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y)
$plusOrMinus *= -1
# Sleep
Start-Sleep -Seconds $sleep
# Announce runtime on an interval
if ( $stopwatch.IsRunning -and (++$index % $announcementInterval) -eq 0 )
{
Write-Host "Elapsed time: " $stopwatch.Elapsed.ToString('dd\.hh\:mm\:ss')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment