0

I'm trying to run a VBScript from within another VBScript without creating a new process. I am able to do it using Powershell like so:

Main Script:

# some main script code here
"&'$scriptPath'" | Invoke-Expression
# some main script code here

In Powershell, the above command runs the PowerShell code inside $scriptPath as if it was a part of the Main script, i.e. running it in the same process.

I would like to achieve this using VBScript.
I've searched the web and aware of objShell.Run "<scriptPath>", but this command is running the code in <scriptPath> in a different process, and not as if it was a part of the main script. Also I'm aware of the option to read the file content and execute it, but I prefer not to if possible.

How this can be achieved using VBScript?

mike
  • 13
  • 4
  • https://stackoverflow.com/a/14235931/11683? – GSerg Mar 23 '20 at 13:17
  • Thank you, reading the file content indeed works fine. I'm trying to find a way to do it without reading the file content if possible (will mention in my post) – mike Mar 23 '20 at 13:29
  • https://social.msdn.microsoft.com/Forums/en-US/adcae113-4758-481a-a367-60d5d14d97d6/this-is-how-to-turn-vbs-and-js-files-into-exe-files-from-the-command-line-without-third-party-tools?forum=scripting –  Mar 23 '20 at 16:27

1 Answers1

0

You'll want to review VBScript's Eval function, and Execute and ExecuteGlobal statements. For example:

Option Explicit

Dim a : a = 8
Dim b : b = 13

' Dynamically inject a new GetSum() Function into this script...
Execute "Function GetSum(ByVal x, ByVal y) : GetSum = x + y : End Function"

' Dynamically call GetSum() with in-script variables and store the result...
Dim result : result = Eval("GetSum(" & CStr(a) & ", " & CStr(b) & ")")

WScript.Echo result

As you can see from above, strings are executed and evaulated in-process without running a separate process or reading a separate file.

For future maintenance efforts and more readable scripts, I might suggest using a .wsf script file rather than .vbs, and place larger string blocks within <resource id="x">...</resource> elements, then read the strings with getResource("x")

Hope this info helps.

leeharvey1
  • 1,316
  • 9
  • 14
  • The problem with this approach is a syntax error in the evaluated string will crash the program. Run time errors will also crash the program if not wrapped in an error handler. Using the MSScript control syntax errors can be caught. See link https://social.msdn.microsoft.com/Forums/en-US/adcae113-4758-481a-a367-60d5d14d97d6/this-is-how-to-turn-vbs-and-js-files-into-exe-files-from-the-command-line-without-third-party-tools?forum=scripting to see how. –  Mar 25 '20 at 17:31