Sometimes, I need to keep my Windows PC awake for a certain period of time. I found a simple PowerShell script that can help me with this.

You can create a PowerShell Script named tt.ps1 with the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Description: Time Travel with PowerShell
# Date: 2024-05-10

$Signature = @'
    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
    public static extern short GetKeyState(int keyCode);'@

Function time_travel($minutes=60, $interval=10, $verbose=$true) {
  Add-Type -AssemblyName System.Windows.Forms
  Add-Type -MemberDefinition $Signature -Name Keyboard -Namespace WeakShell

  $target = (Get-Date).AddMinutes($minutes)

  $totalIterations = ($minutes * 60) / $interval
  $currIter = 0

  $isCapsLocked = $false

  if ($verbose -eq $true) {
    Write-Output "INFO - Start to time travel!"
    Write-Output "INFO - Turn on CapsLock to quit."
    Write-Output ""
  }

  do {
      if ((([int][WeakShell.Keyboard]::GetKeyState(0x14)) -band 0xffff) -eq 0) {
          [System.Windows.Forms.SendKeys]::SendWait("{ScrollLock}")

          $current = Get-Date
          $remain = $target - $current
          $remainIter = $totalIterations - $currIter

          if ($verbose -eq $true) {
            Write-Host "========== ($currIter/$totalIterations) ==========" -ForegroundColor Green
            Write-Host "INFO - Current time: $current"
            Write-Host "INFO - Remaining time: $($remain.TotalMinutes.ToString('F1')) minutes ($remainIter iters)"
          }

          Start-Sleep -Seconds $interval
          $currIter++
      }
      else {
          $isCapsLocked = $true
          Write-Output "INFO - Caps Lock on, Bye!" -ForegroundColor Green
      }
  }while ( ($isCapsLocked -eq $false) -or ((Get-Date) -lt $tar ) )
}

time_travel -minutes 300 -interval 10

Use it with: Right click the file and choose ‘Run with PowerShell’

Reference