Purpose
You want to call up a VBScript function from JavaScript

We generally suggest you use JavaScript or VB.NET exits in GuiXT instead of VBScript. See JavaScript, VBScript or VB.NET? for a comparison of the three options. However, for some tasks VBScript does make sense, since one can find plenty of VBScript samples in the web.

Solution
In our Javacript function we create an "MSScriptControl" object and execute the VBScript code via this scripting host.

You may use the following JavaScript functions for this purpose:

JavaScript framework

 
// vbs.js
// Execute VBScript from JavaScript via scripting host

// execute expression and return result
function vbsExecute(source,textid)
{
   var result = getSH().Eval(source);
   
   if (textid)
   {
     guixt.setText(textid,result);
     return "";
   }
   else
   {
     return result;
   };      
}

// add VBScript functions
function vbsAddCode(textid) {
     var source = guixt.getText(textid);
     getSH().AddCode(source);
}

// create scripting host
var scriptingHost = null;
function getSH() {
    if (!scriptingHost) {
        scriptingHost = 
             guixt.CreateObject("MSScriptControl.ScriptControl");
        scriptingHost.Language = "VBScript";
        scriptingHost.AllowUI = true;
        scriptingHost.TimeOut = 60000; 
    };

    return scriptingHost;
}

		

 

Example 1
We execute a single VBScript statement:

// determine name of month
CallJS
monthname = vbsExecute
"MonthName(8)"

// display the result (test)
Message "&V[monthname]"






Example 2
We read VBScript code from a .vbs file, add the code in the scripting host and execute a VBScript function.

Please observe that adding the code should be done only once; this logic is not implemented in the InputScript below but in Example 3.


VBScript "monthnames.vbs"

Function
  MyMonthName(index, language)
  SetLocale(language) 
  MyMonthName = MonthName(index)
EndFunction


InputScript

// Read VBScript code from .vbs file
CopyText fromFile="monthnames.vbs" toText="code"

// to scripting host
CallJS vbsAddCode "code"

// call up the VBScript function
CallJS monthname = vbsExecute "MyMonthName(8, ""IT"")"

// display the result (test)
Message "&V[monthname]"





Example 3
The user chooses a computer from a drop-down list and then obtains a list of all processes running on this computer:


Click on the image for a larger display 

We also offer an "Excel" button which downloads the data to a CSV file, and a filter button which shows all processes with a CPU activity since the last display.


VBScript "processes.vbs"

' Use WMI (Windows Management Instrumentation) service
' to list the processes on a computer in the local network
Function GetProcesses(computername)
    
    Dim objWMIService, objProcess, colProcess
    OnErrorResumeNext    
    Set objWMIService = _
            GetObject("winmgmts:{impersonationLevel=impersonate}!\\" _
              & computername & "\root\cimv2")
    
    If objWMIService IsNothingThen
      GetProcesses = ""
      Exitfunction
    Endif
    
    Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process")
    
    Dim s
    s = ""
    
    
    ForEach objProcess In colProcess
        With objProcess
            
            If s <> ""Then
                s = s & vbCrLf
            EndIf
            
            s = s & csvString(.ProcessId)  & ";"
            s = s & csvString(LCase(.Name))  & ";"
            s = s & csvString(.Name)  & ";"
            s = s & csvString(GetVBDate(.CreationDate))  & ";"
            s = s & csvString(FormatNumber _
                      (.WorkingSetSize/
1024,0) & " K") & ";"
            s = s & csvString(.Priority) & ";"
            s = s & csvString(FormatNumber _
                      (.UserModeTime/
10/1000,0) & " ms") & ";"
            s = s & csvString(FormatNumber _
                      (.KernelModeTime/
10/1000,0) & " ms") & ";"
            s = s & csvString(FormatNumber _
                      (.ReadOperationCount,
0)) & ";"
            s = s & csvString(FormatNumber _
                      (.WriteOperationCount,
0)) & ";"
            s = s & csvString(FormatNumber _
                      (.WriteTransferCount/
1024,0) & " K") & ";"
            s = s & csvString(FormatNumber(.HandleCount,0)) & ";"
            s = s & csvString(" " & .CommandLine)
        EndWith    
    Next
    
    GetProcesses = s
        
EndFunction

' Date formatting
Function GetVBDate(wd)
  GetVBDate = DateSerial(left(wd,4),mid(wd,5,2),mid(wd,7,2)) _
       + TimeSerial(mid(wd,9,2),mid(wd,11,2),mid(wd,13,2))
EndFunction


' CSV string format, doubling inner "
Function csvString(s)
    
    If s = ""OrVarType(s) = vbNullThen
        csvString = ""
    Else
        csvString = """" & Replace(CStr(s), """", """""") & """"
    EndIf
    
EndFunction


GuiXT Script

// select computer
Text (1,14) "Computer" -label
Set text[computernames] "SC=My PC;server1=Server 1;server2=Server 2"
DropDownList (1,23.2) "computernames" width=41 _
 
refer="V[computername]" process="read_processes.txt"

Pushbutton (1,68) "@42@Refresh" size=(1,15) process="read_processes.txt"
Pushbutton (1,92) "@J2@Excel" size=(1,15) process="excel_processes.txt"
Pushbutton (1,116) "@4G@Active" size=(1,15) process="active_processes.txt"

// create process table
if not V[proc]
  CreateTable V[proc] _
       ProcessId NameLower Name CreationDate WorkingSetSize Priority _
       UserModeTime KernelModeTime _
       ReadOperations WriteOperations WriteTransfers _
       HandleCount CommandLine
endif

if V[computername]
 // process table of selected computer
 
table (3,14) (37,250) name="proc"   _
   
title="&V[proc.rowcount] processes on &V[computername]" _
   
fixedcolumns="12" -rowselection
  column "Name" name="Name" size=30 -readonly
  column "PID" name="ProcessId" size=10 -readonly
  column "Start time" name="CreationDate" size=20 -readonly
  column "WorkingSetSize" name="WorkingSetSize" size=16 -readonly -alignright       
 
column "Priority" name="Priority" size=10 -readonly -alignright
  column "UserModeTime" name="UserModeTime" size=16 -readonly -alignright
  column "KernelModeTime" name="KernelModeTime" size=16 -readonly -alignright
  column "ReadOperations" name="ReadOperations" size=16 -readonly -alignright
  column "WriteOperations" name="WriteOperations" size=16 -readonly -alignright
  column "WriteAmount" name="WriteTransfers" size=16 -readonly -alignright
  column "HandleCount" name="HandleCount" size=12 -readonly -alignright
  column "CommandLine" name="CommandLine" size=68 -readonly
endif


InputScript "read_processes.txt"

// computer selected?
if not V[computername]
  Return "W: Please select a computer" -statusline
endif

// install VBScript code
if not V[proc_code_added]

  // indicate: VBS code loaded
  Set V[proc_code_added] "X"

  // Read VBScript code from a .vbs file
   CopyText fromFile="C:\temp\processes.vbs" toText="code"

  // to scripting host
   CallJS vbsAddCode "code"

endif

// call up the VBScript function
CallJS vbsExecute "GetProcesses(""&V[computername]"")" "csvproc"

// to table
CopyText toTable="V[proc]" fromText="csvproc" delimiter=";"

// sort by name (ignore case)
Sort table="V[proc]" orderby="NameLower,ProcessId"

// reset table display parameters
Clear V[proc.stat.*]

Return


InputScript "excel_processes.txt"

// Excel download (CSV table)

// build temporary filename using TEMP
// environment variable and current time

Set V[tempfile] "&%[TEMP]\guixttemp.&V[today_ymdhms].processes.csv"
CopyText fromTable=V[proc] toText="tempexcel" delimiter=
";"

CopyText fromText="tempexcel" toFile="&V[tempfile]"

Start "&[tempfile]"

Return

 

InputScript "active_processes.txt"

// computer selected?
if
not V[computername]
  Return "W: Please select a computer" -statusline
endif

// save previous results
CopyText fromText="csvproc" toText="csvprocbase"

// call up the VBScript function
CallJS vbsExecute "GetProcesses(""&V[computername]"")" "csvproc"

// create temporary tables of same structure
CreateTable V[proc1] include=V[proc]
CreateTable V[proc2] include=V[proc]
CreateStructure V[procrow1] include=V[proc1]
CreateStructure V[procrow2] include=V[proc2]

// to table
CopyText toTable="V[proc1]" fromText="csvprocbase" delimiter=";"
CopyText toTable="V[proc2]" fromText="csvproc" delimiter=";"

// fill table proc with active processes
Clear V[proc]

Set V[k] 0

label compare
if V[k<&V[proc2.rowcount]]
  Set V[k] &V[k] + 1
 
ReadRow V[procrow2] table=V[proc2] index=&V[k]
  ReadRow V[procrow1] table=V[proc1] key="&V[procrow2.ProcessId]"

// new process, or CPU changed?
 
if not Q[ok] or _
     
not V[procrow1.UserModeTime=&V[procrow2.UserModeTime]] or _
     
not V[procrow1.KernelModeTime=&V[procrow2.KernelModeTime]]

     AppendRow
V[procrow2] table=
V[proc]

  endif

  goto compare

endif

// sort by name (ignore case)
Sort table="V[proc]" orderby="NameLower,ProcessId"

// reset table display parameters
Clear V[proc.stat.*]

Return


Components
InputAssistant + Controls