use vbScript to detect whether the laptop is connecting the power supply

57 Views Asked by At

I have searched for the question. But the code I get has a bug. The detection will be not charging when the battery is full. I'm not familiar with VBScript and windows libraries, thus I'm stuck there.

Here is the code I got and slightly modified from Windows-10 battery indicator Visual Basic Script.

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


Dim prevbCharging
prevbCharging = False
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 (prevbCharging <> bCharging) Then 
  prevbCharging = bCharging
  Dim ws
  Set ws = Wscript.CreateObject("Wscript.Shell")
  if bCharging Then ws.run "cmd /K power-plan.exe 165 & powercfg -SETACTIVE 8C5E7FDA-E8BF-4A96-9A85-A6E23A8C635C",vbhide end if
  if Not bCharging Then ws.run "cmd /K power-plan.exe 60 & powercfg -SETACTIVE 381B4222-F694-41F0-9685-FF5BB260DF2E",vbhide end if
  '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."
  End if
wscript.sleep 600

wend

Could you please offer some help. Thanks!

0

There are 0 best solutions below