06 June 2019

Configuring Power Scheme with a PowerShell One-Liner

Recently, we decided to change the power scheme on machines during the build. This can be quickly done using the powercfg.exe, but I wanted to be sure it always set correctly. Plus, the GUID associated with a power scheme can be different, so I wanted to specify the power scheme by the name.

This PowerShell one-liner will set the power scheme on a machine to the scheme defined in the variable $Setting. If you do a powercfg.exe /l, you will see the name displayed to the right of the GUID in parenthesis. That is what you define in the above variable. The one-liner will then query powercfg to check if it matches the $Setting variable. If it does, it exits with an error code 0. If it does not match, then it sets the power scheme to the GUID from the query and then rechecks to make sure the setting was configured. If it still does not match, then it exits with an error code 1. 

To use this in a one-liner, you need to define the $Setting inside the one-liner below. This may differ on machines, so do the above query to see what is defined in your environment. Place this one-liner in a command line task sequence and you are done.


 powershell.exe -executionpolicy bypass -command "&{$Setting='Balanced';$Output = powercfg.exe /l | Where-Object {$_ -like ('*' + $Setting + '*')};If ($Output.Contains('*') -eq $true) {Write-Host ($Setting + [char]32 + 'is configured');Exit 0} else {$Output = powercfg.exe /s $output.split(' ')[3]; $Output = powercfg.exe /l | Where-Object {$_ -like ('*' + $Setting + '*')};If ($Output.Contains('*') -eq $true) {Write-Host ($Setting + [char]32 + 'Powercfg is configured');Exit 0} else {Write-Host 'Powercfg failed';Exit 1}}}"  

Below is a pic of what it looks like when used in a Run Command Line task sequence. IMO, it makes managing PowerShell scripts easier when they are contained within the task sequence.


Reactions:

0 comments:

Post a Comment