私はWebとStackoverflowを調べてきましたが、この質問に対する答えは見つかりませんでした。Node.jsからPowershellスクリプトをどのように実行しますか?スクリプトは、Node.jsインスタンスと同じサーバー上にあります。
5 に答える
子プロセス「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
これを行うための新しい方法
const { exec } = require('child_process');
exec('command here', {'shell':'powershell.exe'}, (error, stdout, stderr)=> {
// do whatever with stdout
})
受け入れられた答えに加えて、Node.jsと呼ばれるNode.JSライブラリがあり、Node内からさまざまな言語を実行できます。C#、J#、. Net、SQL、Python、PowerShell、その他のCLR言語を含みます。
Edge.jsにはPowerShell3.0が必要であり、Windowsでのみ機能することに注意してください(他の機能の多くはMacとLinuxでも機能します)。
または、 Node-PowerShellを使用することもできます。
Node-PowerShellは、今日のテクノロジーの世界に存在する最もシンプルで効果的で簡単な2つのツールを利用しています。一方では、JavaScriptの世界に革命をもたらしたNodeJSと、他方では、最近最初のオープンソースのクロスプラットフォームバージョンを発表したPowerShellは、それらを相互に接続することで、プログラマー、IT、DevOpsのいずれの場合でも、求められたソリューションを作成します。
このオプションは、スクリプトがまだ存在しない場合に機能しますが、いくつかのコマンドを動的に生成して送信し、結果をノードで処理したい場合に使用します。
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;