Search code examples
vbscriptarguments

Retrieving an argument of a VBScript


How do I pass and return arguments from a VBScript WITHOUT using cscript.exe?

For example, I want to call script2 from script1 that returns a value to script1 without any involvement of cscript.exe. I have searched various answers but they somehow involve the usage of cscript.exe.

This script gets installed voices and sets the one provided in the file voice.txt.

Set WshShell = CreateObject("WScript.Shell")
WShShell.CurrentDirectory = "..\Confirmatory Texts"

Set FSO = CreateObject("Scripting.FileSystemObject")

If FSO.FileExists("voice.txt") Then
  Set temp = FSO.OpenTextFile("voice.txt")
  confirm_voice = temp.ReadLine()
  temp.Close

  Set Sapi = CreateObject("SAPI.SpVoice")

  For Each Voice In Sapi.GetVoices
    i = i + 1
  Next

  For loopvar = 0 To i-1
    If loopvar = CInt(confirm_voice) Then
      Set Sapi.Voice = Sapi.GetVoices.Item(loopvar)
    End If
  Next
Else
  WScript.Echo "An Error Occured"
End If

If I call this script from another script, how can I make this script to return some value to the script that invoked it?


Solution

  • VBScript doesn't really provide call or import mechanisms for other VBScript files. The closest thing is to read the contents of the other file and run them via ExecuteGlobal.

    Demonstration:

    Put the following two files in the same directory and run script1.vbs. It will read the contents of script2.vbs and make the function Square available in the global scope by running the code via ExecuteGlobal. Once the function is available in the global scope you it can be used in the rest of the script.

    script1.vbs:

    Set fso = CreateObject("Scripting.FileSystemObject")
    
    dir    = fso.GetParentFolderName(WScript.ScriptFullName)
    script = fso.BuildPath(dir, "script2.vbs")
    
    ExecuteGlobal fso.OpenTextFile(script).ReadAll  '"import" code into global scope
    
    WScript.Echo Square(3)
    

    script2.vbs:

    Function Square(i)
      Square = i*i
    End Function