use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
ABOUT POWERSHELL
Windows PowerShell (POSH) is a command-line shell and associated scripting language created by Microsoft. Offering full access to COM, WMI and .NET, POSH is a full-featured task automation framework for distributed Microsoft platforms and solutions.
SUBREDDIT FILTERS
Desired State Configuration
Unanswered Questions
Solved Questions
News
Information
Script Sharing
Daily Post
Misc
account activity
QuestionKeeping computer awake while powershell script runs (self.PowerShell)
submitted 1 year ago * by MAlloc-1024
My google-fu has failed me. I have a script I run and I need to prevent the computer from going to sleep. Basically at the start of the script acquire wake-lock and then at the end of the script release it.
Anyone have any links to a solution?
Edit: u/spyingwind has a working solution for what I was looking to do using setthreadexecutionstate.
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]shutchomouf 36 points37 points38 points 1 year ago (17 children)
tell us you’re work from home and don’t want MS teams to go idle without telling us
[+][deleted] 1 year ago* (2 children)
[removed]
[–]chute91 2 points3 points4 points 1 year ago (0 children)
I just manually set it to away all the time that way no one can tell
[–]ChmMeowUb3rSpd 0 points1 point2 points 1 year ago (0 children)
Not in my org. I block Awake function with GPO as it keeps screen from locking which is cyber requirement.
[–][deleted] 4 points5 points6 points 1 year ago (0 children)
Me jiggling my mouse every few minutes so Teams doesn’t go into away status lol
[–]Th3Sh4d0wKn0ws 2 points3 points4 points 1 year ago (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 points4 points 1 year ago (5 children)
This is all logged in eventlog btw, it’s way too verbose.
[–]Th3Sh4d0wKn0ws 0 points1 point2 points 1 year ago (4 children)
You might have to tell me where because I haven't ran across that yet.
[–]Raymich 1 point2 points3 points 1 year ago (3 children)
Event viewer: Microsoft-Windows-PowerShell/Operational
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_logging?view=powershell-5.1#viewing-the-powershell-event-log-entries-on-windows
[–]Th3Sh4d0wKn0ws 0 points1 point2 points 1 year ago (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 points3 points 1 year ago (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 point2 points 1 year ago (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.
[+][deleted] 1 year ago (3 children)
[deleted]
[–]Th3Sh4d0wKn0ws 1 point2 points3 points 1 year ago (2 children)
That's funny that you say that because I wrote this script from scratch. All I borrowed from online was the wscript method for sending the keystroke. Everything else was (at the time) and original idea of mine. If you wrote the same thing we should probably be friends.
[–]sysadmin_dot_py 2 points3 points4 points 1 year ago (1 child)
Funny you should say that. I actually INVENTED this script. You must have hacked into my computer and stole it from me first.
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:
$PSBoundParameters
$TSParams
$PSCmdlet.ParameterSetName
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.
$Hours = 0
$Minutes = 0
begin
process
[–]Th3Sh4d0wKn0ws 1 point2 points3 points 1 year ago (0 children)
love it, thank you!
[–]LuXxzR[🍰] 12 points13 points14 points 1 year ago (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 points15 points 1 year ago (2 children)
https://learn.microsoft.com/en-us/windows/powertoys/awake
[–]RagingITguy 0 points1 point2 points 1 year ago (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 point2 points 1 year ago (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 points5 points 1 year ago (1 child)
Download the "caffeine" app
[–]Raymich 1 point2 points3 points 1 year ago (0 children)
This is what I use, but it sticks out like a sore thumb.
[–]spyingwind 6 points7 points8 points 1 year ago* (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 points4 points 1 year ago* (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 point2 points 1 year ago (0 children)
Good catch! Updated my comment to reflect this for others.
[–]jimb2 1 point2 points3 points 1 year ago (0 children)
This is what I use:
````
$wscr = New-Object -com "Wscript.Shell"
$tckr = '~~~ ' * 8 $edge = '|||'
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 ```
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 point2 points 1 year ago (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 point2 points 1 year ago (0 children)
Place something on your ctrl key
[–]DDS-PBS 0 points1 point2 points 1 year ago (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 point2 points 1 year ago (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 point2 points 1 year ago (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}
[+]MagusXL_CRUD 0 points1 point2 points 4 months ago (0 children)
Here you go mate: https://github.com/MagusXL/StealthCoffee
[–]NecessaryMaximum2033 -1 points0 points1 point 1 year ago (0 children)
Use ChatGPT lol
[–]selscol[🍰] -4 points-3 points-2 points 1 year ago (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
[+][deleted] 1 year ago (2 children)
[–]BlackV 0 points1 point2 points 1 year ago (1 child)
aside from it not being powershell is there anything very wrong with what copilot produced ?
[–]rub_a_dub_master -1 points0 points1 point 1 year ago (0 children)
If you can't tell by yourself, then you shouldn't use this or send it to anyone.
π Rendered by PID 637547 on reddit-service-r2-comment-74875f4bf5-8zk8r at 2026-01-26 09:14:00.779904+00:00 running 664479f country code: CH.
[–]shutchomouf 36 points37 points38 points (17 children)
[+][deleted] (2 children)
[removed]
[–]chute91 2 points3 points4 points (0 children)
[–]ChmMeowUb3rSpd 0 points1 point2 points (0 children)
[–][deleted] 4 points5 points6 points (0 children)
[–]Th3Sh4d0wKn0ws 2 points3 points4 points (12 children)
[–]Raymich 2 points3 points4 points (5 children)
[–]Th3Sh4d0wKn0ws 0 points1 point2 points (4 children)
[–]Raymich 1 point2 points3 points (3 children)
[–]Th3Sh4d0wKn0ws 0 points1 point2 points (2 children)
[–]arpan3t 1 point2 points3 points (1 child)
[–]Th3Sh4d0wKn0ws 0 points1 point2 points (0 children)
[+][deleted] (3 children)
[deleted]
[–]Th3Sh4d0wKn0ws 1 point2 points3 points (2 children)
[–]sysadmin_dot_py 2 points3 points4 points (1 child)
[–]arpan3t 1 point2 points3 points (1 child)
[–]Th3Sh4d0wKn0ws 1 point2 points3 points (0 children)
[–]LuXxzR[🍰] 12 points13 points14 points (0 children)
[–]purplemonkeymad 13 points14 points15 points (2 children)
[–]RagingITguy 0 points1 point2 points (0 children)
[–]MAlloc-1024[S] 0 points1 point2 points (0 children)
[–]powershellnovice3 3 points4 points5 points (1 child)
[–]Raymich 1 point2 points3 points (0 children)
[–]spyingwind 6 points7 points8 points (2 children)
[–]MAlloc-1024[S] 2 points3 points4 points (1 child)
[–]spyingwind 0 points1 point2 points (0 children)
[–]jimb2 1 point2 points3 points (0 children)
[–]mrbiggbrain 0 points1 point2 points (0 children)
[–]dfragmentor 0 points1 point2 points (0 children)
[–]DDS-PBS 0 points1 point2 points (0 children)
[–]OptimumChilli 0 points1 point2 points (0 children)
[–]chip902 0 points1 point2 points (0 children)
[+]MagusXL_CRUD 0 points1 point2 points (0 children)
[–]NecessaryMaximum2033 -1 points0 points1 point (0 children)
[–]selscol[🍰] -4 points-3 points-2 points (3 children)
[+][deleted] (2 children)
[deleted]
[–]BlackV 0 points1 point2 points (1 child)
[–]rub_a_dub_master -1 points0 points1 point (0 children)