Grab just the GUID from powercfg /list

426 Views Asked by At

Working on a Caffinate Alternative for Windows and was wondering if there was a way I could grab just the GUID of the current used powerplan without the rest of the output heres a example of what I mean.

What I am getting... when using powercfg /list

Existing Power Schemes (* Active)
-----------------------------------
Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e  (Balanced) *

What I want...

381b4222-f694-41f0-9685-ff5bb260df2e

This is so I can refrence it and reload it in once caffinate is finished.

2

There are 2 best solutions below

0
On
@ECHO OFF
SETLOCAL
FOR /f "tokens=1-4" %%g IN ('powercfg /list^|find "*" ') DO IF "%%g%%h%%i"=="PowerSchemeGUID:" SET "guid=%%j"
ECHO guid=%guid%
GOTO :EOF

If you want other guids from the list, simply substitute Balanced High performance or Power saver (or whatever else you may need) for *

0
On

Get Current Power Scheme GUID

To get the current power scheme, use -getactivescheme instead of -list (Powercfg Docs):

powercfg -getactivescheme
# Power Scheme GUID: 49371465-2b86-4782-9e84-816d3f61e3c8  (Ultimate Performance)

In Powershell, we can use Regex to extract the GUID:

[regex]::Match((powercfg -getactivescheme), 'GUID: ([\w-]+)').Groups[1].Value
# 49371465-2b86-4782-9e84-816d3f61e3c8

List All Power Scheme GUIDs

[regex]::Matches((powercfg -list), 'GUID: ([\w-]+)') | %{$_.Groups[1].Value}

[regex]::Match Explanation

We're using [regex] to access the .NET regex methods Match and Matches. Run [regex] | Get-Member -Static for a list of other methods. The basic syntax of Match and Matches is:

[regex]::Match($stringToMatch, $regexPattern)

Match returns the first match, Matches returns a collection of matches.

To list all power scheme GUIDs, we use [regex]::Matches on the list of power schemes and pipe the result to a ForEach. %{} is shorthand for ForEach. $_ represents the current item in the loop. In this case, our MatchInfo objects.