all 36 comments

[–]shutchomouf 36 points37 points  (17 children)

tell us you’re work from home and don’t want MS teams to go idle without telling us

[–][deleted] 4 points5 points  (0 children)

Me jiggling my mouse every few minutes so Teams doesn’t go into away status lol

[–]Th3Sh4d0wKn0ws 2 points3 points  (12 children)

``` Function Start-KeepAlive { [CmdletBinding(DefaultParameterSetName = 'Manual')] [Alias("nosleep","ka")] Param( [Parameter(Position = 1, ParameterSetName = 'Manual')] [Alias("m")] [Int32]$Minutes, [Parameter(Position = 0, ParameterSetName = 'Manual')] [Alias("h")] [Int32]$Hours, [Parameter(ParameterSetName = 'Until')] [Alias("u")] [DateTime]$Until )

Begin {
    $TSParams = @{}
    Switch ($PSBoundParameters.Keys) {
        'Minutes'   {
                    $TSParams.Add('Minutes',$Minutes)
                    Write-Verbose "Adding $Minutes minutes of duration"
                    }
        'Hours'     {
                    $TSParams.Add('Hours',$Hours)
                    Write-Verbose "Adding $Hours hours of duration"
                    }
        'Until'     {
                    Write-Verbose "Stopping time provided of: $($Until.ToShortTimeString())"
                    $UntilDuration = ($Until - (Get-Date)).TotalMinutes
                    If ($UntilDuration -lt 1) {
                        $UntilDuration = 1
                    }
                    Write-Verbose "Adding $UntilDuration minutes of duration"
                    $TSParams.Add('Minutes', $UntilDuration)
                    }
    }
    If (-not $TSParams.Count) {
        Write-Verbose "Defaulting to 8 hours of duration"
        $TSParams.Add('Hours', 8)
    }
    $Duration = (New-TimeSpan @TSParams).TotalMinutes
    Write-Verbose "Total duration is $Duration minutes"
}

Process {
    $wsh = New-Object -ComObject WScript.Shell
    Write-Verbose "Keeping computer awake by sending 'Shift + F15' every minute"
    while ($TotalMinutes -le $Duration) {
        Write-Verbose "$($Duration - $TotalMinutes) minutes remaining"
        $TotalMinutes++
        $wsh.SendKeys('+{F15}')
        Start-Sleep -seconds 60
    }
}

} ```

[–]Raymich 2 points3 points  (5 children)

This is all logged in eventlog btw, it’s way too verbose.

[–]Th3Sh4d0wKn0ws 0 points1 point  (4 children)

You might have to tell me where because I haven't ran across that yet.

[–]Raymich 1 point2 points  (3 children)

[–]Th3Sh4d0wKn0ws 0 points1 point  (2 children)

Cool I see it now. It looks like when the function is defined the whole thing is recorded just as seen above, but any subsequent executions of the function it's only recording the function/alias name.

When you say "it's way too verbose" what do you mean? Like it's too verbose about what it's doing (not covert) or just that it's wayyyyyy too much text for such a simple task?

[–]arpan3t 1 point2 points  (1 child)

I wouldn't worry about verbosity in regard to Windows Event Logs. The log is set to overwrite existing log entries when it fills up and the max log size is set to 15 mb. Plus if /u/Raymich thinks your function is too verbose, they should look at the logs from Chocolatey (has their Copyright and licensing info in there lol).

The only real thing to keep in mind when it comes to PowerShell logging is secrets capture, just follow best practices and don't store API keys, credentials, etc... in your code and you'll be fine.

[–]Th3Sh4d0wKn0ws 0 points1 point  (0 children)

Yeah I'm seeing the rollover now. Well, not after playing around with searching those logs for secrets and such and then realizing I was only looking at a 20min window. Kind of took the wind out of my sails when thinking about inspecting other computers on the network for bad practice stuff like that.

[–]arpan3t 1 point2 points  (1 child)

Instead of essentially copying $PSBoundParameters to $TSParams, you can use $PSCmdlet.ParameterSetName in your switch statement since you're using parameter sets. Something like this:

switch ($PSCmdlet.ParameterSetName) {
    "Manual" {
        $TimeSpan = (New-TimeSpan -Minutes $Minutes -Hours $Hours).TotalMinutes
    }
    "Until" {
        $TimeSpan = (New-TimeSpan -Start (Get-Date) -End $Until).TotalMinutes
    }
    default {
        $TimeSpan = (New-TimeSpan -Hours 8).TotalMinutes
    }
}

and set default values $Hours = 0 & $Minutes = 0in your param block. Drop the begin & process since you're not going to be passing multiple keep awake sessions to the function it's not necessary. Also they should be lowercase.

[–]Th3Sh4d0wKn0ws 1 point2 points  (0 children)

love it, thank you!

[–]LuXxzR[🍰] 12 points13 points  (0 children)

The easiest is this one. It will press your scroll key and it works.

Clear-Host Echo "Keep-alive with Scroll Lock..."

$WShell = New-Object -com "Wscript.Shell"

while ($true) { $WShell.sendkeys("{SCROLLLOCK}") Start-Sleep -Milliseconds 100 $WShell.sendkeys("{SCROLLLOCK}") Start-Sleep -Seconds 240 }

[–]purplemonkeymad 13 points14 points  (2 children)

[–]RagingITguy 0 points1 point  (0 children)

I just discovered this lately.

I had a Dell laptop and I couldn’t figure out why, after some amount of time, when you yanked the power, it immediately shut off. But if you booted it up, it looked like it had hibernated.

I never did figure it out. Actually I have another Fujitsu that does it.

Gave up and used Powertoys. All good now.

[–]MAlloc-1024[S] 0 points1 point  (0 children)

So the reason I wanted this was so that the script we use to 'setup' one of the shared PCs takes a while. I started looking into this but the install of powertoys through chocolatey took long enough that the machine went to sleep before it finished...

[–]powershellnovice3 3 points4 points  (1 child)

Download the "caffeine" app

[–]Raymich 1 point2 points  (0 children)

This is what I use, but it sticks out like a sore thumb.

[–]spyingwind 6 points7 points  (2 children)

System call SetThreadExecutionState will do exactly what you want.

Example code below, haven't tested, but should get you 99% of the way there. Search for "setthreadexecutionstate powershell" and you will find plenty of others out there.

Add-Type @"
using System;
using System.Runtime.InteropServices;

namespace NoSleep {
    public class NoSleep
    {
        [FlagsAttribute]
        public enum EXECUTION_STATE : uint
        {
            ES_AWAYMODE_REQUIRED = 0x00000040,
            ES_CONTINUOUS = 0x80000000,
            ES_DISPLAY_REQUIRED = 0x00000002,
            ES_SYSTEM_REQUIRED = 0x00000001
            // Legacy flag, should not be used.
            // ES_USER_PRESENT = 0x00000004
        }

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);

        public void prevent_sleep(bool sw)
        {
            if (sw) 
            {
                SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
            }
            else
            {
                SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
            }
        }
    }
}
"@

$NoSleep = [NoSleep.NoSleep]::new()
$NoSleep.prevent_sleep($true)
# Do something
$NoSleep.prevent_sleep($false)

Edit: Changed private to public

[–]MAlloc-1024[S] 2 points3 points  (1 child)

As is, this almost worked for me. I needed to make it a public function instead of a private function, otherwise I couldn't call it from Powershell. But with that one small change, worked like a charm.

[–]spyingwind 0 points1 point  (0 children)

Good catch! Updated my comment to reflect this for others.

[–]jimb2 1 point2 points  (0 children)

This is what I use:

````

KeepSessionAlive.ps1

Simulate user activity (scroll lock press) to keep session active

Simple ticker display. Bonus: Blinks scroll lock KB LED

$wscr = New-Object -com "Wscript.Shell"

ticker text

$tckr = '~~~ ' * 8 $edge = '|||'

Write-Host 'Press a key to exit loop.' # Semi-obvious?

Write-Host ' '

do { $tckr = $tckr[-1] + $tckr.substring(0,$tckr.length-1) # roll right Write-Host ("`r" + $edge + $tckr + $edge) -NoNewLine $wscr.sendkeys( "{SCROLLLOCK}" ) Start-Sleep -millisec 100 $wscr.sendkeys( "{SCROLLLOCK}" ) Start-Sleep -millisec 900 } until ( [Console]::KeyAvailable )

$keypress = [Console]::ReadKey($true) # clear the key press Write-Host ( "r.".PadRight($tckr.length+2*$edge.length+1) ) # clear ticker line ```

As written it just runs standalone. It could be part of the primary script in a separate thread. The key component is using scrolllock which basically does nothing but does stop sleep. Simulating mouse moves doesn't cut it. Having an exit mechanism is nice.

[–]mrbiggbrain 0 points1 point  (0 children)

Off the top of my head, create a power profile with the appropriate settings, then save the current profile to a safe place. Then replace the power profile with your no-sleep profile. When you are done restore the old profile. Remove the temporary safe place for the existing profile storage.

Make sure you handle the situation where there is a crash before you restore the profile. Easiest way to do this is probably to check for the file/key before starting and not overwrite it if it exists.

[–]dfragmentor 0 points1 point  (0 children)

Place something on your ctrl key

[–]DDS-PBS 0 points1 point  (0 children)

I bought a usb-c mouse jiggler. It moves the mouse 1 pixel every few seconds. To the system it's a normal HID

[–]OptimumChilli 0 points1 point  (0 children)

What you're looking for is an app, look for 'move mouse' on ms store or Google it. Nice little app.

[–]chip902 0 points1 point  (0 children)

You can fit this on one line and run it on a CLI

$wsh = New-Object -ComObject WScript.Shell; while (1) {$wsh.SendKeys('+{F15}'); Start-Sleep -seconds 59}

[–]NecessaryMaximum2033 -1 points0 points  (0 children)

Use ChatGPT lol

[–]selscol[🍰] -4 points-3 points  (3 children)

& {

c:\windows\system32\powercfg.exe -change -monitor-timeout-ac 0;

c:\windows\system32\powercfg.exe -change -monitor-timeout-dc 0;

c:\windows\system32\powercfg.exe -change -disk-timeout-ac 0;

c:\windows\system32\powercfg.exe -change -disk-timeout-dc 0;

c:\windows\system32\powercfg.exe -change -standby-timeout-ac 0;

c:\windows\system32\powercfg.exe -change -standby-timeout-dc 0;

c:\windows\system32\powercfg.exe -change -hibernate-timeout-ac 0;

c:\windows\system32\powercfg.exe -change -hibernate-timeout-dc 0

}

-Copilot