Sunday, March 11, 2012

Windows 7 Power Management via PowerShell

Recently, I was asked to develop a small script to turn off sleep and hibernate as well as remove the lid closing policy for machines that are using AC Power.  After many attempts to accomplish this in many different ways, I found that the way that works best across different language sets for the Windows Operating System is by using the registry entries for each of the specific entries.  I also wanted to include the ability to change these 3 settings for every power plan on the machine.

Below, you will find the code I am using:

# Stop the machine from going to sleep after 20 minutes.
Write-Host "Removing the automated sleep functionality"
$pwrKey = Get-ChildItem -Path HKLM:\SYSTEM\CurrentControlSet\Control\Power\PowerSettings\238C9FA8-0AAD-41ED-83F4-97BE242C8F20\29f6c1db-86da-48c5-9fdb-f2b67b1f44da\DefaultPowerSchemeValues

ForEach ($pwr in $pwrKey) {
    $Subkey = $pwr.PSChildName
    Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Power\PowerSettings\238C9FA8-0AAD-41ED-83F4-97BE242C8F20\29f6c1db-86da-48c5-9fdb-f2b67b1f44da\DefaultPowerSchemeValues\$Subkey -Value 0 -Name "ACSettingIndex"
}

# Stop the machine from going into hibernate
Write-Host "Removing the automated hibernate functionality"
$pwrKey = Get-ChildItem -Path HKLM:\SYSTEM\CurrentControlSet\Control\Power\PowerSettings\238C9FA8-0AAD-41ED-83F4-97BE242C8F20\9d7815a6-7ee4-497e-8888-515a05f02364\DefaultPowerSchemeValues

ForEach ($pwr in $pwrKey) {
    $Subkey = $pwr.PSChildName
    Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Power\PowerSettings\238C9FA8-0AAD-41ED-83F4-97BE242C8F20\9d7815a6-7ee4-497e-8888-515a05f02364\DefaultPowerSchemeValues\$Subkey -Value 0 -Name "ACSettingIndex"
}

# Lid Closing Policy
Write-Host "Removing the Lid Closing Policy"
$pwrKey = Get-ChildItem -Path HKLM:\SYSTEM\CurrentControlSet\Control\Power\PowerSettings\4f971e89-eebd-4455-a8de-9e59040e7347\5ca83367-6e45-459f-a27b-476b1d01c936\DefaultPowerSchemeValues

ForEach ($pwr in $pwrKey) {
    $Subkey = $pwr.PSChildName
    Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Power\PowerSettings\4f971e89-eebd-4455-a8de-9e59040e7347\5ca83367-6e45-459f-a27b-476b1d01c936\DefaultPowerSchemeValues\$Subkey -Value 0 -Name "ACSettingIndex"
}