Windows 7 – How to Script the ‘Sleep’ Command

hybrid-sleeppower-managementsleepwindows 7

To clarify, when I'm talking about 'Sleep' I mean Hybrid Sleep, i.e. save the contents of RAM to the hibernation file and then go in to Standby mode.

I have this working perfectly fine via the start menu, but want to script it in the form of something that can be run by the Task Scheduler. An exe, batch script or Powershell script would work well

I've experimented with PowrProf SetSuspendState and powercfg -h off in scripts with no luck, it always just goes straight into Standby or hibernates and turns off entirely

Best Answer

I figured out my solution from this VERY helpful answer by user @jnL (please upvote his contribution!) It works on my win7 HP lappy and makes it "sleep" in the same way as if I selected Sleep from the Windows Start Menu GUI, i.e.

Keeps your session in memory and puts the computer in
a low-power state so that you can quickly resume
working.

Now that I've added this script to my PowerShell profile C:\Users\user_name\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

function sleepy_time {
Add-Type -AssemblyName System.Windows.Forms
$PowerState = [System.Windows.Forms.PowerState]::Suspend;
$Force = $false;
$DisableWake = $false;
[System.Windows.Forms.Application]::SetSuspendState($PowerState, $Force, $DisableWake);
}

new-alias -name nap -value sleepy_time

...when I enter nap at the PowerShell prompt my laptop goes to sleep, fan spins down and then when I move the mouse or press spacebar (etc...) it wakes up to a login screen.

Note that the rundll32.exe solution apparently corrupts the stack, per a comment in this thread by user @accolade referencing this answer: https://superuser.com/a/331545/21887

Related Question