我想自动设置 Windows 7 在我的工作笔记本电脑上合上盖子时执行的操作,因为每次我登录时都会通过 GPO 重置。
我知道我可以在批处理脚本中使用 powercfg 命令来实现这一点:
powercfg -setacvalueindex 5ca83367-6e45-459f-a27b-476b1d01c936 0
powercfg -setdcvalueindex 5ca83367-6e45-459f-a27b-476b1d01c936 0
但是,这是尝试学习一些 powershell 的好借口。我的第一次尝试需要 10 多秒才能运行。
在运行时和代码的清洁度方面,我如何改进以下内容。解决以下问题的惯用 powershell 方式是什么?
$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()