Execute Powershell script from Node.js

2019-01-07 08:41发布

I've been looking around the web and on Stackoverflow but hadn't found an answer to this question. How would you execute a Powershell script from Node.js? The script is on the same server as the Node.js instance.

4条回答
\"骚年 ilove
2楼-- · 2019-01-07 09:20

You can just spawn a child process "powershell.exe" and listen to stdout for command output and stderr for errors:

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
查看更多
别忘想泡老子
3楼-- · 2019-01-07 09:32

In addition to the accepted answer, there is a Node.JS Library called Edge.js that allows various langugages to be executed from within Node. Including C#, J#, .Net, SQL, Python, PowerShell and other CLR languages.

Note that Edge.js requires PowerShell 3.0 & only works on Windows (many of the other features work on Mac and Linux too).

查看更多
劳资没心,怎么记你
4楼-- · 2019-01-07 09:37

This option works for me, when the script is not already there, but you want to generate some commands dynamically, send them, and work with the results back on node.

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;
查看更多
等我变得足够好
5楼-- · 2019-01-07 09:42

Or you can just use Node-PowerShell.

Node-PowerShell taking advantage of two of the simplest, effective and easy tools that exist in the today technology world. On the one hand, NodeJS which made a revolution in the world of javascript, and on the other hand, PowerShell which recently came out with an initial open-source, cross-platform version, and by connecting them together, gives you the power to create any solution you were asked to, no matter if you are a programmer, an IT or a DevOps guy.

查看更多
登录 后发表回答