1

I'm trying to runs specific parameterized powershell scripts. Below is a working example

var spawn = require("child_process").spawn,child;

child = spawn("powershell.exe",["c:\\test\\mypstest.ps1 -arg1 1"]);
     child.stdout.on("data",function(data){
     console.log("Powershell Data: " + data);
});
     child.stderr.on("data",function(data){
     console.log("Powershell Errors: " + data);
});
child.on("exit",function(){
     console.log("Powershell Script finished");
});

child.stdin.end(); //end input

Here is an example ps script

param(
    [int]$arg1 = 0
    )

function test(){
    If ($arg1 -eq 0){
    write-host 'too bad'
    }

    If ($arg1 -eq 1){
        calc
    }

    If ($arg1 -eq 2){ 
        notepad
    }
}
test

But I need to be able to pass the variables as the arguments for the ps script. I thought this would work.

var str2 = "\"c:\\test\\mypstest.ps1 -arg1";
var str3 = " 1\"";

var mystr1 = str2.concat(str3);

child = spawn("powershell.exe",[mystr1]);

I also tried

function myfunc1(param1, param2){
    var mystr1 = str2.concat(str3);
    //console.log(mystr1);
    return mystr1;
    };

child = spawn("powershell.exe",[myfunc1(str2, str3)]);

But i appear to be passed back the variable itself, below is the output i get from the console

Powershell Data: c:\test\mypstest.ps1 -arg1 1

Powershell Script finished

And tried this

var str1 = "\"powershell.exe\"\,";
var str2 = "\[\"c:\\test\\mypstest.ps1 -arg1";
var str3 = " 1\"\]";

function myfunc1(param1, param2, param3){
    var mystr1 = str1.concat(str2, str3);
    console.log(mystr1);
    return mystr1;
    };

child = spawn(myfunc1(str1, str2, str3));

for the above i get an exception

events.js:72 throw er; // Unhandled 'error' event Error: spawn ENOENT at errnoException (child_process.js:998:11) at Process.ChildProcess._handle.onexit (child_process.js:789:34)

i'm not fluent in js so any help would be appreciated

1 Answer 1

2
var str2 = "\"c:\\test\\mypstest.ps1 -arg1";
var str3 = " 1\"";

var mystr1 = str2.concat(str3);

...will generate the resulting string;

"c:\test\mypstest.ps1 -arg1 1"

...while what you want according to your working version is an un-quoted version;

c:\test\mypstest.ps1 -arg1 1

Remove the extra quotes from your string, and it should be equivalent with your working example.

Sign up to request clarification or add additional context in comments.

1 Comment

wow, not sure how i missed that, that did it. Must have been starring at it to long. appreciate the quick response

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.