'Windows-10 battery indicator Visual Basic Script

I got some code from the internet for a warning indicator. I use it for warning me when battery is charging and the battery level is above 80%.

But I also want to use it to warn me when the battery level is below 20%. I have added a line for this 20% warning, but it is not working. It works when battery is above 80%, but not when battery is below 20%.

I think the code is in Visual Basic Script (VBS).

Please help.

I have already searched on other forums and this one, but could not find such a program anywhere.

set oLocator = CreateObject("WbemScripting.SWbemLocator")
set oServices = oLocator.ConnectServer(".","root\wmi")
set oResults = oServices.ExecQuery("select * from batteryfullchargedcapacity")
for each oResult in oResults
   iFull = oResult.FullChargedCapacity
next

while (1)
  set oResults = oServices.ExecQuery("select * from batterystatus")
  for each oResult in oResults
    iRemaining = oResult.RemainingCapacity
    bCharging = oResult.Charging
  next
  iPercent = ((iRemaining / iFull) * 100) mod 100
  if bCharging and (iPercent > 80) Then msgbox "Battery is charged now more than 80%. Please stop charging for optimal battery life."
  if bCharging and (iPercent < 20) Then msgbox "Battery is discharging and is below 20%. Please switch on charging immediately."
  wscript.sleep 30000 ' 5 minutes
wend


Solution 1:[1]

If you need one that monitors 2 or more batteries in one laptop:

set oLocator = CreateObject("WbemScripting.SWbemLocator")
set oServices = oLocator.ConnectServer(".","root\wmi")
set oResults = oServices.ExecQuery("select * from batteryfullchargedcapacity")
 
for each oResult in oResults
    iFull = oResult.FullChargedCapacity
next
 
while (1)
    set oResults = oServices.ExecQuery("select * from batterystatus")
    totalRemaining = 0
    batteryCount = 0
    for each oResult in oResults
        iRemaining = oResult.RemainingCapacity
        bCharging = oResult.Charging
        totalRemaining = totalRemaining + iRemaining
        batteryCount = batteryCount + 1
    next
    iPercent = Round(((totalRemaining / batteryCount) / iFull) * 100)
    
    if bCharging and (iPercent > 80) Then msgbox "Battery is charged now more than 80%. Please stop charging for optimal battery life."
    if not bCharging and (iPercent < 20) Then msgbox "Battery is discharging and is below 20%. Please switch on charging immediately."
  wscript.sleep 3000000 ' sleep for 5 minutes

wend

Solution 2:[2]

change - if bCharging and (iPercent < 20) to if iRemaining and (iPercent < 20) because bCharging is While Plugged in and iRemaining is While on Battery

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 QwertyForever
Solution 2 Eric Aya