从Node.js执行Powershell脚本

我一直在环视networking和Stackoverflow,但没有find这个问题的答案。 你将如何从Node.js执行Powershell脚本? 该脚本与Node.js实例位于同一台服务器上。

你可以产生一个subprocess“powershell.exe”,并听命令输出和标准错误的标准输出:

var spawn = require("child_process").spawn,child; child = spawn("powershell.exe",["c:\\temp\\helloworld.ps1"]); 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 

除了被接受的答案之外,还有一个名为Edge.js的Node.JS库,允许在Node内执行各种语言。 包括C#,J#,.Net,SQL,Python, PowerShell和其他CLR语言。

请注意,Edge.js需要PowerShell 3.0,并且只能在Windows上运行(许多其他function也可以在Mac和Linux上运行)。

这个选项适用于我,当脚本不在那里,但你想dynamic地生成一些命令,发送它们,并在结点上处理结果。

 var PSRunner = { send: function(commands) { var self = this; var results = []; var spawn = require("child_process").spawn; var child = spawn("powershell.exe", ["-Command", "-"]); child.stdout.on("data", function(data) { self.out.push(data.toString()); }); child.stderr.on("data", function(data) { self.err.push(data.toString()); }); commands.forEach(function(cmd){ self.out = []; self.err = []; child.stdin.write(cmd+ '\n'); results.push({command: cmd, output: self.out, errors: self.err}); }); child.stdin.end(); return results; }, }; module.exports = PSRunner; 

或者你可以使用Node-PowerShell 。

Node-PowerShell利用当今技术世界中存在的两个最简单,有效和简单的工具。 一方面,在JavaScript的世界里进行了一场革命的NodeJS,另一方面,最近推出了一个最初的开源,跨平台版本的PowerShell,并将它们连接在一起,为您提供了强大的function无论您是程序员,IT还是DevOps人员,都可以创build您要求的任何解决scheme。