Hello from Money Manager
[CmdletBinding()]
param(
[ValidateSet('IdleOnly', 'FixedInterval')]
[string] $Mode = 'IdleOnly',
[ValidateNotNullOrEmpty()]
[string] $Key = '{F15}',
[ValidateRange(0.1, 86400)]
[double] $IntervalSeconds = 60,
[ValidateRange(0.1, 86400)]
[double] $IdleSeconds = 60,
[ValidateRange(0, 31536000)]
[double] $DurationSeconds = 0,
[ValidateRange(0.1, 3600)]
[double] $StatusRefreshSeconds = 1,
[switch] $NoStatus
)
function Get-KeepAwakeDelay {
param(
[string] $Mode,
[double] $Elapsed,
[double] $LastSent,
[double] $Interval,
[double] $IdleThreshold,
[double] $Idle
)
$intervalDelay = [Math]::Max(0.0, $Interval - ($Elapsed - $LastSent))
if ($Mode -eq 'IdleOnly') {
return [Math]::Max($intervalDelay, [Math]::Max(0.0, $IdleThreshold - $Idle))
}
return $intervalDelay
}
function Format-KeepAwakeTime {
param([double] $Seconds)
$time = [TimeSpan]::FromSeconds([Math]::Floor([Math]::Max(0.0, $Seconds)))
return '{0:D2}:{1:D2}:{2:D2}' -f [int][Math]::Floor($time.TotalHours), $time.Minutes, $time.Seconds
}
function Invoke-KeepAwakeLoop {
param(
[string] $Mode,
[double] $Interval,
[double] $IdleThreshold,
[double] $Duration,
[double] $Refresh,
[scriptblock] $GetElapsed,
[scriptblock] $GetIdle,
[scriptblock] $SendKey,
[scriptblock] $Wait,
[scriptblock] $ShowStatus
)
$lastSent = 0.0
while ($true) {
$elapsed = [double] (& $GetElapsed)
if ($Duration -gt 0 -and $elapsed -ge $Duration) {
break
}
$idle = 0.0
if ($Mode -eq 'IdleOnly') {
$idle = [double] (& $GetIdle)
}
$delay = Get-KeepAwakeDelay -Mode $Mode -Elapsed $elapsed -LastSent $lastSent `
-Interval $Interval -IdleThreshold $IdleThreshold -Idle $idle
if ($delay -le 0) {
# Recheck the deadline immediately before sending.
$elapsed = [double] (& $GetElapsed)
if ($Duration -gt 0 -and $elapsed -ge $Duration) {
break
}
& $SendKey
$lastSent = [double] (& $GetElapsed)
continue
}
$remaining = if ($Duration -gt 0) { [Math]::Max(0.0, $Duration - $elapsed) } else { [double]::PositiveInfinity }
& $ShowStatus $elapsed $delay $remaining
$sleepSeconds = [Math]::Min($Refresh, [Math]::Min($delay, $remaining))
& $Wait $sleepSeconds
}
}
function Initialize-KeepAwakeIdleApi {
if (-not ('Jigglers.LastInput' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace Jigglers {
public static class LastInput {
[StructLayout(LayoutKind.Sequential)]
private struct LASTINPUTINFO {
public uint cbSize;
public uint dwTime;
}
[DllImport("user32.dll", SetLastError = true)]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO info);
[DllImport("kernel32.dll")]
private static extern uint GetTickCount();
public static double IdleSeconds() {
LASTINPUTINFO info = new LASTINPUTINFO();
info.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO));
if (!GetLastInputInfo(ref info)) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return ElapsedSeconds(GetTickCount(), info.dwTime);
}
public static double ElapsedSeconds(uint current, uint last) {
return unchecked(current - last) / 1000.0;
}
}
}
'@
}
}
function Start-KeepAwake {
param(
[string] $Mode,
[string] $Key,
[double] $Interval,
[double] $IdleThreshold,
[double] $Duration,
[double] $Refresh,
[bool] $NoStatus
)
foreach ($value in @($Interval, $IdleThreshold, $Duration, $Refresh)) {
if ([double]::IsNaN($value) -or [double]::IsInfinity($value)) {
throw 'Timing values must be finite numbers.'
}
}
if ([string]::IsNullOrWhiteSpace($Key)) {
throw 'Key must be a non-empty WScript SendKeys expression.'
}
if ($env:OS -ne 'Windows_NT' -or -not [Environment]::UserInteractive) {
throw 'This script requires an interactive Windows desktop session.'
}
if ($Mode -eq 'IdleOnly') {
Initialize-KeepAwakeIdleApi
}
$shell = $null
$progressEnabled = -not $NoStatus -and $Host.Name -eq 'ConsoleHost' -and -not [Console]::IsOutputRedirected
try {
$shell = New-Object -ComObject WScript.Shell -ErrorAction Stop
$clock = [Diagnostics.Stopwatch]::StartNew()
Write-Host "Keep-awake running ($Mode, key: $Key). Press Ctrl+C to stop."
Write-Host 'Keys are sent to the focused application; Windows and Teams may ignore synthetic input.'
$getElapsed = { $clock.Elapsed.TotalSeconds }
$getIdle = { [Jigglers.LastInput]::IdleSeconds() }
$sendKey = { $shell.SendKeys($Key) }
$wait = {
param($seconds)
Start-Sleep -Milliseconds ([int][Math]::Max(1, [Math]::Ceiling($seconds * 1000)))
}
$showStatus = {
param($elapsed, $delay, $remaining)
if (-not $NoStatus) {
$elapsedText = Format-KeepAwakeTime $elapsed
if ($remaining -le $delay) {
$nextText = 'none before duration ends'
}
else {
$nextText = 'about {0}s (estimated {1})' -f `
([Math]::Ceiling($delay)), (Get-Date).AddSeconds($delay).ToString('HH:mm:ss')
}
$status = "Elapsed $elapsedText | Next key: $nextText"
if ($progressEnabled) {
Write-Progress -Activity "Keep-awake ($Mode)" -Status $status
}
else {
Write-Output "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') $status"
}
}
}
Invoke-KeepAwakeLoop -Mode $Mode -Interval $Interval -IdleThreshold $IdleThreshold `
-Duration $Duration -Refresh $Refresh -GetElapsed $getElapsed -GetIdle $getIdle `
-SendKey $sendKey -Wait $wait -ShowStatus $showStatus
Write-Host 'Keep-awake duration completed.'
}
finally {
if ($progressEnabled) {
Write-Progress -Activity "Keep-awake ($Mode)" -Completed
}
if ($null -ne $shell) {
[void] [Runtime.InteropServices.Marshal]::FinalReleaseComObject($shell)
}
}
}
if ($MyInvocation.InvocationName -ne '.') {
Start-KeepAwake -Mode $Mode -Key $Key -Interval $IntervalSeconds -IdleThreshold $IdleSeconds `
-Duration $DurationSeconds -Refresh $StatusRefreshSeconds -NoStatus $NoStatus.IsPresent
}