Hello everyone,
I’m trying to create a script to list all available sleep states for a device, so I’m running ‘powercfg /a’ and I tried to create a regex expression to extract the lines that interest me and it seems to show what I need → regex101: build, test, and debug regex
But when I run the below code, I don’t get any result - what am I doing wrong here
?
…
$SleepStates = powercfg /a
$RegexSleepStates = “(?smi)((?<=The following sleep states are available on this system:\n).?$.+?^\n?$)”
select-string -inputobject $SleepStates -Pattern $RegexSleepStates -AllMatches | ForEach-Object { $.Matches } | ForEach-Object { $.Value }
…
Hi Karol,
First issue I see if you’re trying to span multiple lines when the input is going to be line by line. Typically you would just make it a single string value rather than an array of strings, but I had weirdness with the output. Probably something to do with the way powershell reencodes the output. So instead of helping fix your attempt, I offer an alternative solution.
$capture = $false
switch -Regex (powercfg /a){
'The following sleep states are available on this system:' {
$capture = $true
}
'^\s{2,4}(.+$)' {
if($capture){
$matches.1
}
}
'The following sleep states are not available on this system:' {$capture = $false}
}
Please give it a try while waiting for others to offer input. If you want to capture the output to a variable just put the variable assignment before the switch statement.
$capture = $false
$MyVariable = switch -Regex (powercfg /a){
'The following sleep states are available on this system:' {
$capture = $true
}
'^\s{2,4}(.+$)' {
if($capture){
$matches.1
}
}
'The following sleep states are not available on this system:' {$capture = $false}
}
Hi Doug,
thank you very much for your help!
Your code does exactly what I needed 
The construct you proposed is quite complicated for my current PS/Regex skills, but I’ll go over it a couple of times until I understand it.