从Node.js执行Powershell脚本

gv8xihay  于 2023-11-17  发布在  Node.js
关注(0)|答案(4)|浏览(166)

我一直在网上和Stackoverflow上寻找,但没有找到这个问题的答案。你如何从Node.js执行Powershell脚本?该脚本与Node.js示例位于同一个服务器上。

uelo1irk

uelo1irk1#

你可以只生成一个子进程“powershell.exe”,并监听stdout的命令输出和stderr的错误:

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

字符串

50pmv0ei

50pmv0ei2#

更新的方法是

const { exec } = require('child_process');
exec('command here', {'shell':'powershell.exe'}, (error, stdout, stderr)=> {
    // do whatever with stdout
})

字符串

w6lpcovy

w6lpcovy3#

这个选项对我来说很有用,当脚本还没有在那里,但是你想动态地生成一些命令,发送它们,然后在节点上处理结果。

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;

字符串

e37o9pze

e37o9pze4#

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

字符串

**注意:**在Windows中,Powershell脚本可以根据您运行此脚本的路径添加,而无需考虑完整路径。

相关问题