1

I want to run a powershell script when i close the lid on a laptop with windows 10, if there isn't an external monitor attached to te pc, it goes sleep. The script works well if i lauch it manually, but i cannot find inside task scheduler an activation event like 'closing the lid'.

Here should be the activation event

This is the powershell script:

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 
if ( @(Get-CimInstance -Namespace root\wmi -ClassName WmiMonitorBasicDisplayParams | where-object { $_.Active }).Length -eq 1 )
{
    #put laptop to sleep if there are no external monitor connected
    $PowerState = [System.Windows.Forms.PowerState]::Suspend;
    $Force = $true;
    $DisableWake = $false;
    [System.Windows.Forms.Application]::SetSuspendState($PowerState, $Force, $DisableWake);
}
kevin256
  • 31
  • 6
  • You can give [this](https://social.technet.microsoft.com/Forums/en-US/a5f9d579-00c7-49fd-9bf4-a13ef1a01c93/task-scheduler-on-laptop-lid-close?forum=w7itproui) a shot. – Abraham Zinala Aug 27 '22 at 20:20
  • i tried it, but it doesn't work, i think that the kernel-power event with id 42 is the 'going sleep' event, but the laptop shouldn't go automatically to sleep but should before run the powershell script to detect if there is an external monitor connected – kevin256 Aug 27 '22 at 20:28
  • not familiar with it at all, but here's [something](https://stackoverflow.com/questions/10988662/registerpowersettingsnotification-c-sharp-pinvoke) you may want to try. – Abraham Zinala Aug 27 '22 at 21:01
  • 1
    We all have a reason for X or Y thingy, but... I don't get your issue here. You set this state in the 'OS Power Options' manually or via GPO/LPO policy. You only have to do this once. I cannot fathom a reason to run a script for this. [Here is a SO discussion on setting this state via PS if you really wanted to, but again, it's a one-time thing, so why do it](https://stackoverflow.com/questions/15455864/powershell-set-lid-close-action). Automation is about doing regular repetitive tasks in a consistent way. – postanote Aug 28 '22 at 01:23
  • The problem is that if there is an external monitor connected the laptop must not go to sleep, while if there are no monitors connected it must go to sleep. In the 'OS Power Option' there isn't an option that let me choose what to do when there are or not external monitor connected. And i don't want a program that run always in background that check if the li is closed or open and than put the laptop in sleep if needed – kevin256 Aug 28 '22 at 10:17

0 Answers0