Controlling the Windows Power Plan with PowerShell

I’ve been using a Windows laptop for presenting while traveling. Yes, it’s heavy. Yes, it’s big. Yes, it’s weird compared to my MacBook. But, it works.

More Power, More Problems

When I’m on a plane, I want to make sure that I’m getting every last drop of power out of the battery. When I’m presenting, I want to power up the CPUs so I’m not getting weird results in demos because of power saving in the CPU. I’m also lazy and, frequently, I don’t have a mouse next to me while I present.

More PowerShell

Thanks to Robert Davis’s post Enabligh High Perofrmance Power Plan via PowerShell, I knew that I could use a pretty simple command to switch the power plan:``` Try { $HighPerf = powercfg -l | %{if($.contains(“High performance”)) {$.split()[3]}} $CurrPlan = $(powercfg -getactivescheme).split()[3] if ($CurrPlan -ne $HighPerf) {powercfg -setactive $HighPerf} } Catch { Write-Warning -Message “Unable to set power plan to high performance” }

### More Modules

I could have created multiple functions in my PowerShell profile, but instead I created a module. The first step, really, was to create a file with a bunch of code in it. After banging around for a while, I came up with:```
function Set-PowerPlan ($powerPlan = "balanced") {
    try {
        $powerPlan = $powerPlan.toLower()
        $perf = powercfg -l | %{if($_.toLower().contains($powerPlan)) {$_.split()[3]}}
        $currentPlan = $(powercfg -getactivescheme).split()[3]

        if ($currentPlan -ne $perf) {
            powercfg -setactive $perf
    } catch {
        Write-Warning -Message "Unabled to set power plan to $powerPlan"

function Set-PowerSaver {
    Set-PowerPlan("power saver")

function Set-PowerHighPerformance {
    Set-PowerPlan("high performance")

function Set-PowerBalanced {
```This uses some basic string matching magic to try to match a power plan. I _could_ keep using the`Set-PowerPlan` commandlet to change the power plan, but that's a lot of typing. Since I don't add new power plans to Windows, I created three shortcuts to set the power plan for me.

### Reusing the Module

The basic steps to module re-use are:

1.  Create an appropriately named folder in your `Modules` folder. Mine is named `PowerPlan`.
2.  Create a file in the module folder. This was also called `PowerPlan.psm1`.
3.  Check that the module is available using `Get-Module -ListAvailable`.
4.  If available, run `Import-Module PowerPlan`.

If you always want the PowerPlan module loaded, you can added the line `Import-Module PowerPlan` to your PowerShell profile (which defaults ot `Microsoft.PowerShell_profile.ps1`). Once I've imported the module, I just have to open up a PowerShell window and type `Set-Power` and then I can use `TAB` to cycle through the possible completions.