【发布时间】: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