title: Powershell Set Lid Close Action
body: <p>I wanted to automate setting the action Windows 7 takes when the lid is closed on my work laptop, as this is reset via GPO every time i login.</p>
  
  <p>I know that i can use the powercfg command in a batch script to achieve this:</p>
  
  <pre><code>powercfg -setacvalueindex 5ca83367-6e45-459f-a27b-476b1d01c936 0
  powercfg -setdcvalueindex 5ca83367-6e45-459f-a27b-476b1d01c936 0
  </code></pre>
  
  <p>However, this was a good excuse to attempt learning some powershell. My first attempt takes over 10 seconds to run.</p>
  
  <p>How can i improve on the below, both in terms of runtime &amp; in terms of cleanliness of the code. What would be the idiomatic powershell way to approach the below?</p>
  
  <pre><code>$DO_NOTHING = 0
  
  $activePowerPlan = Get-WmiObject -Namespace "root\cimv2\power" Win32_PowerPlan | where {$_.IsActive}
  $rawPowerPlanID = $activePowerPlan | select -Property InstanceID
  $rawPowerPlanID -match '\\({.*})}'
  $powerPlanID = $matches[1]
  
  # The .GetRelated() method is an inefficient approach, i'm looking for a needle and this haystack is too big. Can i go directly to the object instead of searching?
  $lidCloseActionOnACPower = $activePowerPlan.GetRelated("win32_powersettingdataindex") | where {$_.InstanceID -eq "Microsoft:PowerSettingDataIndex\$powerPlanID\AC\{5ca83367-6e45-459f-a27b-476b1d01c936}"}
  $lidCloseActionOnBattery = $activePowerPlan.GetRelated("win32_powersettingdataindex") | where {$_.InstanceID -eq "Microsoft:PowerSettingDataIndex\$powerPlanID\DC\{5ca83367-6e45-459f-a27b-476b1d01c936}"}
  
  $lidCloseActionOnACPower | select -Property SettingIndexValue
  $lidCloseActionOnACPower.SettingIndexValue = $DO_NOTHING
  $lidCloseActionOnACPower.put()
  
  $lidCloseActionOnBattery | select -Property SettingIndexValue
  $lidCloseActionOnBattery.SettingIndexValue = $DO_NOTHING
  $lidCloseActionOnBattery.put()
  </code></pre>