When running installations, some systems are set to lock after a certain period of inactivity even though the installation is running in the background. Recently I was testing CIS Group Policy policies and my labs kept locking and it becomes frustrating to keep having to unlock so I have a script to simulate a keypress such as the spacebar to keep the session alive and it worked.

Below is a video (no sound, just a screen record) of PowerShell running in the background and notepad in the foreground, showing the blue space between the two letters shrinking:

Below is the code with comments, you can modify it to suite your needs. The following fields can be adjusted:

  • $totalMinutes (in my script it is set to 920)
    $totalMinutes = 920

function SimulateKeyPress {
    # Create a shell object
    $shell = New-Object -ComObject "WScript.Shell"
    # Simulate a keypress (spacebar)
    $shell.SendKeys(" ")

function Main {
    # Calculate total seconds
    $totalSeconds = $totalMinutes * 60
    for ($i = 0; $i -lt $totalSeconds; $i += 30) {
        # Call the function to simulate keypress

        # Pause for 30 seconds
        Start-Sleep -Seconds 30

# Execute the main function

I hope it helps you if you have a problem with screen locking or logging out set by GPO or other methods. You can run it straight in PowerShell without having to save it.

Hope it helps.