【问题标题】:How do I pass variables to powershell through node js如何通过节点js将变量传递给powershell
【发布时间】:2014-07-10 08:18:57
【问题描述】:

我正在尝试运行特定的参数化 powershell 脚本。下面是一个工作示例

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

这是一个示例 ps 脚本

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

但我需要能够将变量作为 ps 脚本的参数传递。我认为这会起作用。

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

var mystr1 = str2.concat(str3);

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

我也试过

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

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

但我似乎被传回了变量本身,下面是我从控制台得到的输出

Powershell 数据:c:\test\mypstest.ps1 -arg1 1

Powershell 脚本完成

并尝试了这个

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));

对于上述情况,我得到了一个例外

events.js:72 投掷者; // 未处理的“错误”事件 错误:生成 ENOENT 在 errnoException (child_process.js:998:11) 在 Process.ChildProcess._handle.onexit (child_process.js:789:34)

我不精通 js,所以任何帮助将不胜感激

【问题讨论】:

    标签: javascript node.js powershell


    【解决方案1】:
    var str2 = "\"c:\\test\\mypstest.ps1 -arg1";
    var str3 = " 1\"";
    
    var mystr1 = str2.concat(str3);
    

    ...将生成结果字符串;

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

    ...而根据您的工作版本,您想要的是未引用的版本;

    c:\test\mypstest.ps1 -arg1 1
    

    从您的字符串中删除多余的引号,它应该与您的工作示例等效。

    【讨论】:

    • 哇,不知道我是怎么错过的,就是这样。一定是主演了很久。感谢快速响应
    猜你喜欢
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多