44

私はWebとStackoverflowを調べてきましたが、この質問に対する答えは見つかりませんでした。Node.jsからPowershellスクリプトをどのように実行しますか?スクリプトは、Node.jsインスタンスと同じサーバー上にあります。

4

5 に答える 5

83

子プロセス「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
于 2012-04-16T20:49:01.217 に答える
27

これを行うための新しい方法

const { exec } = require('child_process');
exec('command here', {'shell':'powershell.exe'}, (error, stdout, stderr)=> {
    // do whatever with stdout
})
于 2020-04-15T01:24:26.710 に答える
13

受け入れられた答えに加えて、Node.jsと呼ばれるNode.JSライブラリがあり、Node内からさまざまな言語を実行できます。C#、J#、. Net、SQL、Python、PowerShell、その他のCLR言語を含みます。

Edge.jsにはPowerShell3.0が必要であり、Windowsでのみ機能することに注意してください(他の機能の多くはMacとLinuxでも機能します)。

于 2014-07-09T16:29:20.557 に答える
13

または、 Node-PowerShellを使用することもできます。

Node-PowerShellは、今日のテクノロジーの世界に存在する最もシンプルで効果的で簡単な2つのツールを利用しています。一方では、JavaScriptの世界に革命をもたらしたNodeJSと、他方では、最近最初のオープンソースのクロスプラットフォームバージョンを発表したPowerShellは、それらを相互に接続することで、プログラマー、IT、DevOpsのいずれの場合でも、求められたソリューションを作成します。

于 2017-03-03T16:47:52.287 に答える
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;
于 2014-10-03T03:13:04.673 に答える