Skip to content

Instantly share code, notes, and snippets.

@webtroter
Created August 5, 2025 16:27
Show Gist options
  • Select an option

  • Save webtroter/1e11ff8f4ac00871348d84bc9a87dfe3 to your computer and use it in GitHub Desktop.

Select an option

Save webtroter/1e11ff8f4ac00871348d84bc9a87dfe3 to your computer and use it in GitHub Desktop.
Invoke-Caffeine - To keep your computer from Sleeping
function Invoke-Caffeine {
param (
[string]$Key = '{F15}',
[int]$Delay = 30
)
begin {
# Create WScript.Shell COM object
$wshell = New-Object -ComObject WScript.Shell
# Create a stopwatch to track elapsed time
$stopwatch = [System.Diagnostics.Stopwatch]::new()
}
process {
try {
while ($true) {
$stopwatch.Start()
$wshell.SendKeys($Key)
Write-Host -NoNewline '.'
Start-Sleep -Seconds $Delay
}
}
catch {
Write-Host "`nFunction interrupted."
}
finally {
$stopwatch.Stop()
Write-Host -Object '.'
Write-Information -MessageData ("Kept awake for {0:n0}m{1}s" -f $stopwatch.Elapsed.TotalMinutes, $stopwatch.Elapsed.Seconds) -InformationAction Continue
Write-Information -MessageData $stopwatch.Elapsed -Tags Timer
Write-Information -MessageData ("Elapsed time: {0}" -f $stopwatch.Elapsed.ToString("d\.hh\:mm\:ss")) -Tags @("Timer", "ToString")
}
}
end {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment