Advanced program start-up and killing | On charge/plug-in

AgejevDominik

New Member
Hi,

First of all, I'm sorry if this isn't the right place to post this kind of question. If you know where I can post this please let me know.
Onto the question.
I'd like to start a program (Rainmeter) when I plug in my laptop to charge, I would also like to kill it when I plug it out, i.e. stop charging. I'd like the program to run while the laptop is at a 100% while plugged in (so it's not actually charging but it's plugged in).
The reason I am trying to do this is because Rainmeter drains a lot of power. I might add other programs in the future.
Can I do this with the Task Scheduler? (If so, how?)
I can do basic coding in Python and C++ but I don't know how to interact with other programs and definitely not with the machine itself.

Thanks in advance
 

Neemobeer

Windows Forum Team
Staff member
You could launch the following Powershell script on user logon. Just change the paths in the first line to whatever you want to start and stop.

Code:
$RunApplicationsOnAC = @("C:\Windows\notepad.exe","C:\Windows\System32\cmd.exe")


Function Get-IsOnACPower
{
    return (Get-WmiObject -Namespace root\WMI -Class BatteryStatus).PowerOnline
}


Function Main
{
    $PowerState = Get-IsOnACPower
    while($true)
    {
        $CurrentPowerStatus = Get-IsOnACPower

        if($PowerState -ne $CurrentPowerStatus)
        {
            $PowerState = $CurrentPowerStatus
            
            # Power status has changed to on AC Power (plugged in)
            if($PowerState)
            {
                foreach($RunApplicationOnAC in $RunApplicationsOnAC)
                {
                    Start-Process -FilePath $RunApplicationOnAC -Wait:$false
                }
            }
            else
            {
                foreach($RunApplicationOnAC in $RunApplicationsOnAC)
                {
                    $ProcessName = (Split-Path -Leaf $RunApplicationOnAC).Replace(".exe","")
                    Stop-Process -Name $ProcessName -Force -ErrorAction SilentlyContinue
                }
            }
          
        }

        if($PowerState)
        {
            foreach($RunApplicationOnAC in $RunApplicationsOnAC)
            {
                $ProcessName = (Split-Path -Leaf $RunApplicationOnAC).Replace(".exe","")
                try
                {
                    Get-Process -Name $ProcessName -ErrorAction Stop | Out-Null
                }
                catch
                {
                    Start-Process $RunApplicationOnAC -Wait:$false
                }
            }
        }

        Start-Sleep -Seconds 5
    }
}

Main
 
Top