我正在尝试使用powershell从powercfg
. 我有足够的信息将范围缩小到设置的子组,但在文本块中我仍然需要使用 GUID 找到匹配的设置,然后我需要提取设置的当前设置值。我能够使用 来实现这一点Select-String -Context
,但它不是动态的,因此容易出错。我正在寻找一种更清洁的方法来提取价值。
这是我拥有的文本块的示例(存储在 中$block
):
Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)
GUID Alias: SCHEME_BALANCED
Subgroup GUID: 238c9fa8-0aad-41ed-83f4-97be242c8f20 (Sleep)
GUID Alias: SUB_SLEEP
Power Setting GUID: 29f6c1db-86da-48c5-9fdb-f2b67b1f44da (Sleep after)
GUID Alias: STANDBYIDLE
Minimum Possible Setting: 0x00000000
Maximum Possible Setting: 0xffffffff
Possible Settings increment: 0x00000001
Possible Settings units: Seconds
Current AC Power Setting Index: 0x00000708
Current DC Power Setting Index: 0x00000384
Power Setting GUID: 94ac6d29-73ce-41a6-809f-6363ba21b47e (Allow hybrid sleep)
GUID Alias: HYBRIDSLEEP
Possible Setting Index: 000
Possible Setting Friendly Name: Off
Possible Setting Index: 001
Possible Setting Friendly Name: On
Current AC Power Setting Index: 0x00000001
Current DC Power Setting Index: 0x00000001
Power Setting GUID: 9d7815a6-7ee4-497e-8888-515a05f02364 (Hibernate after)
GUID Alias: HIBERNATEIDLE
Minimum Possible Setting: 0x00000000
Maximum Possible Setting: 0xffffffff
Possible Settings increment: 0x00000001
Possible Settings units: Seconds
Current AC Power Setting Index: 0x00002a30
Current DC Power Setting Index: 0x00002a30
Power Setting GUID: bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d (Allow wake timers)
GUID Alias: RTCWAKE
Possible Setting Index: 000
Possible Setting Friendly Name: Disable
Possible Setting Index: 001
Possible Setting Friendly Name: Enable
Possible Setting Index: 002
Possible Setting Friendly Name: Important Wake Timers Only
Current AC Power Setting Index: 0x00000001
Current DC Power Setting Index: 0x00000001
假设我想提取 的 AC 值Allow hybrid sleep
,在本例中为0x00000001
。我setting_guid
可以插入到查询字符串中。
现在我正在使用这段代码来动态提取特定设置的值:
$block = powercfg /q #{scheme_guid} #{sub_guid}
$setting = $block | Select-String -Pattern #{setting_guid} -Context 0, 8 | %{$_.Context.PostContext}
$line = $setting | Select-String -Pattern 'Current #{ac_or_dc} Power Setting Index'
$line -match 'Current #{ac_or_dc} Power Setting Index: (?<value>0x.{8})'
Write-Output ([int]$matches['value'])
目前这很好用,但硬编码-Context 0, 8
并不是很理想,因为有时块可能很短或很长,我的查询将无法提取值,或者它会从错误的行中检索。我希望找到一种更简洁的方法来做到这一点,最好是程序化和人类可读的(只要有意义,正则表达式就可以了)。