我有这个PowerShell,我通常称之为:
powershell -ExecutionPolicy Bypass -File "D:\tmp\getmember2.ps1" -groupnames "ABC"
现在,我需要从我的nodejs调用它。所以,这就是我创造的:
var spawn = Meteor.npmRequire("child_process").spawn;
child = spawn("powershell.exe",["-ExecutionPolicy ByPass -File d:\\tmp\\getmember2.ps1 -groupnames \"ABC\""]);
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();
但是我收到了这个错误:
I20170222-16:58:25.257(8)? API started
I20170222-16:58:26.175(8)? Powershell Errors: At line:1 char:2
I20170222-16:58:26.174(8)?
I20170222-16:58:26.175(8)? + CategoryInfo : ParserError: (-:String)
[], ParentContainsErrorR
I20170222-16:58:26.175(8)? + - <<<< ExecutionPolicy ByPass -File d:\tmp\getmember2.ps1
I20170222-16:58:26.176(8)? Powershell Errors: ecordException
I20170222-16:58:26.176(8)? Powershell Errors: + FullyQualifiedErrorId : MissingExpressionAfterOperator
I20170222-16:58:26.176(8)? Powershell Errors:
I20170222-16:58:26.177(8)?
I20170222-16:58:26.174(8)? Powershell Errors: Missing expression after unary operator '-'.
I20170222-16:58:26.259(8)? Powershell Script finished
有关为什么不起作用的任何想法?
答案 0 :(得分:0)
将我的代码更改为使用child_process.exec()而不是spawn()。 如此link中所述:
当您希望子进程将大量数据返回到节点 - 图像处理,读取二进制数据等时,最好使用Spawn。使用exec运行返回结果状态而不是数据的程序。
代码更改为以下并整齐地运行我的powershell。
var child = exec('Powershell.exe -executionpolicy ByPass -File d:\\tmp\\getmember.ps1 -processdir d:\\temp -groupnames "ABC"',
function(err, stdout, stderr){
//callback(err)
if(err){
console.error(err);
}else {
console.log("should be no issue");
}
});
child.stdout.on('data', function(data) {
// Print out what being printed in the powershell
console.log(data);
});
child.stderr.on('data', function(data) {
//print error being printed in powershell
console.log('stderr: ' + data);
});
child.on('close',function(code){
// To check the result of powershell exit code
console.log("exit code is "+code);
if(code==0)
{
console.log("Powershell run successfully, exit code = 0 ")
}else {
console.log("ERROR, powershell exited with exit code = "+ code);
}
});
child.stdin.end();