从Node.js执行Powershell脚本

61

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

4个回答

93

你可以创建一个子进程"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

4
我知道这个问题有点老,但是 PowerShell 可以使用管理员权限运行吗? - Vandervidi
@Vandervidi 看看 node-windows npm 包。它提供了一个名为 elevate 的函数,可能是你正在寻找的东西。 - muffel
1
有没有办法将相对路径作为第二个参数传递给PowerShell脚本? - Andrew Kostenko
1
如何从Node.js传递脚本文件的参数 - Ramyachinna
原则上这很好,但对于路径中包含嵌入空格的脚本不起作用;通常最好通过-File参数调用脚本(并使用-NoProfile参数以实现可预测性),这也使传递参数更容易:child = spawn("powershell.exe", [ '-noprofile', '-file', "c:\\temp\\helloworld.ps1", "arg1", "arg2"])。在没有-File的情况下,会隐含-Command(在Windows PowerShell中,而不是PowerShell Core)。/cc @Ramyachinna - mklement0
显示剩余3条评论

51

新的方法来做这件事

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

1
谢谢!用这个解决方案解决了! - writingdeveloper
你如何让它与外部 PowerShell 脚本配合工作? - Big Money
将脚本作为字符串读入,并用变量替换“command here”。 - Honest Objections
我在npm仓库中查找了child_process,发现在此链接https://www.npmjs.com/package/child_process下的Read Me章节中有如下信息: 安全保持包 - 此软件包名称目前未使用,但以前被另一个软件包占用。 同时它只有一个版本而且已经有7年历史了。 只是想确保我找到了正确的那个。 - Alwaysa Learner
1
@AlwaysaLearner child_process是一个内置的包。https://nodejs.org/docs/latest-v18.x/api/child_process.html - Johan Dahl
1
@AlwaysaLearner child_process 是一个内置的包。https://nodejs.org/docs/latest-v18.x/api/child_process.html - Johan Dahl

10
这个选项对我很有用,当脚本尚不存在但您想动态生成一些命令、发送它们并在节点上使用结果时。
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;

这样做不会将所有错误和输出添加到最后执行的命令中吗?我在这里寻求了一些帮助:(https://stackoverflow.com/questions/66778574/how-is-this-used-in-a-function-and-is-it-required?noredirect=1#comment118046903_66778574)。 - DarkLite1

1
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脚本,而不受完整路径的限制。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接