B4J Tutorial Execute Windows VBS-Scripts from B4J

I needed to read the remaining battery charge from my laptop acting as a server to give an alert if the charge is under xx %. There are a lot of examples to use a vbs-script to gather this information and others (just browse the www for vbs & get xxxx).

To call this little helpers from B4J and get the output follow this little example.

Lib needed: jShell

B4J-Code (non-ui but you can use it in ui apps with no change)

B4X:
'Non-UI application (console / server application)
#Region  Project Attributes
    #CommandLineArgs:  
    #MergeLibraries: True
#End Region

Sub Process_Globals
  
End Sub

Sub AppStart (Args() As String)
  
    Log("Reading battery status...")
    Dim BatterySh As Shell
    BatterySh.Initialize("Battery", "c:\windows\system32\cscript.exe", Array As String("//nologo", "C:\Users\Klaus\Documents\B4JApps\WinBattery\battery.vbs"))
    BatterySh.WorkingDirectory = "C:\Users\Klaus\Documents\B4JApps\WinBattery\"
    BatterySh.Run(120000)
  
    StartMessageLoop
End Sub



Sub Battery_ProcessCompleted (Success As Boolean, ExitCode As Int, StdOut As String, StdErr As String)
   If Success And ExitCode = 0 Then
     If IsNumber(StdOut) Then
         Dim ChargeRemaining As Int = StdOut
        Log ("Charge remainig: " & ChargeRemaining)
     Else
         Log("Oops... Battery not found...")
     End If
   
   Else
     Log("Error: " & StdErr & StdOut)
  
   End If
 
End Sub

Note:

- The vbs-script is called as a parameter via cscript.exe (= the batch interpreter of windows). You can't call it directly
- the //nologo parameter is like "echo off". It prevents cscript.exe to prompt "(c) Microsoft....".

VBS-Script "battery.vbs":

B4X:
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_Battery",,48)
For Each objItem in colItems
    Wscript.Echo objItem.EstimatedChargeRemaining
Next

How to use:

Just create a new folder and put the B4J app in it. Same dir for the vbs-script. Adjust the path's to it and have fun (of course it's better to use File.DirApp or similar).

I've tested it under WIN10

Hints:

You can call any vbs script :) So new features are available to your B4J app which Java.FX maybe does not provide. Maybe you want to use Word and do a mail merge or convert a document to PDF :)

If you need to pass more parameters just expand the array and play with it (it took me some tries how to use the //nologo parameter)
 
Top