Search code examples
evaljscriptwsh

Execute JScript code stored as a string and pass arguments


So I've read Execute JavaScript code stored as a string and looked at this simple answer.

My question, what if the JScript code, stored in the string, expects arguments? how to I pass it?

First try:

var jsStr = "WScript.Echo(WScript.Arguments[0]);";
eval(jsStr);

Second try:

var F = new Function(jsStr);
F.call(this,'test str');

But this poor attempt failed.

Note:

Let's assume the I have no control on jsStr value. So basically, reformatting it is out of the question at this moment.


Solution

  • The problem is caused by the []. WScript.Arguments is an object (provided by the script host runtime), but not an array. To access its elements, you have to use (), i.e. call its Item() function. Evidence:

    var jsStr;
    jsStr = "WScript.Echo('a', WScript.Arguments(0));"; eval(jsStr);
    jsStr = "WScript.Echo('b', WScript.Arguments.Item(0));"; eval(jsStr);
    
    var expr;
    expr = "typeof WScript.Arguments"; WScript.Echo(0, expr, eval(expr));
    expr = "typeof WScript.Arguments(0)"; WScript.Echo(1, expr, eval(expr));
    expr = "typeof WScript.Arguments[0]"; WScript.Echo(2, expr, eval(expr));
    

    output:

    cscript 27250366.js pipapo
    a pipapo
    b pipapo
    0 typeof WScript.Arguments object
    1 typeof WScript.Arguments(0) string
    2 typeof WScript.Arguments[0] undefined