Windows11でバッテリー残量20%以下と80%以上をチェックしたかったので、ネットで調べてVBScriptで作成。
バッテリーチェックはほぼそのまま使えるのが多くあったけど、トースト通知は無かったので難しかった。
Option Explicit
Dim oLocator, oServices, oResults, oResult
Dim iFull
Dim iRemaining, bCharging
Dim iPercent
Set oLocator = CreateObject("WbemScripting.SWbemLocator")
Set oService = oLocator.ConnectServer(".","root\wmi")
' フル充電量を取得
Set oResults = oService.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
' 充電中で80%以上の場合
If bCharging and (iPercent >= 80) Then
Notify "バッテリーチェック", "バッテリーは " & iPercent & "%です。充電を終了してください。"
MsgBox "バッテリーは " & iPercent & "%です。充電を終了してください。", vbInformation, "バッテリーチェック"
End If
' 充電無で20%以下の場合
If Not(bCharging) and (iPercent <= 20) Then
Notify "バッテリーチェック", "バッテリーは " & iPercent & "%です。充電してください。"
MsgBox "バッテリーは " & iPercent & "%です。充電してください。", vbInformation, "バッテリーチェック"
End If
' スリープ。ミリ秒指定で5分。
WScript.Sleep 300 * 1000
Wend
' 通知
Public Function Notify(ByVal title, ByVal msg)
Const PSpath = "powershell.exe"
Dim WsShell
Dim strCommand
' 実行するpowershellを指定
strCommand = """" & PSpath & """ -Command " & Chr(34) & "& { "
strCommand = strCommand & "$ToastText02 = [Windows.UI.Notifications.ToastTemplateType, Windows.UI.Notifications, ContentType = WindowsRuntime]::ToastText02"
strCommand = strCommand & "; $TemplateContent = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]::GetTemplateContent($ToastText02)"
strCommand = strCommand & "; $TemplateContent.GetElementsByTagName('text').Item(0).InnerText = '" & title & "'"
strCommand = strCommand & "; $TemplateContent.GetElementsByTagName('text').Item(1).InnerText = '" & msg & "'"
strCommand = strCommand & "; $AppId = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe'"
strCommand = strCommand & "; [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($AppId).Show($TemplateContent)"
strCommand = strCommand & " }" & Chr(34)
' powershellを実行
Set oShell = CreateObject("WScript.Shell")
oShell.Run strCommand, 0, False
End Function
実行前に必要な設定
トースト通知にPowershellを使用しているので、Powershellの実行権限が必要。
デフォルトだと「Restricted」で実行できないはずで、以下のコマンドで権限付与。
※各オプションの意味を確認の上ご利用を。
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
現在の設定は以下で確認可能。
Get-ExecutionPolicy
終了方法
VBScriptを終了させる場合はタスクマネージャーから「Microsoft Windows Based Script Host」を終了させる。
Windows11だとタスクマネージャーのプロセスタブよりユーザタブのほうが見つけやすかった。