我在网上和Stackoverflow上寻找答案,但没有找到这个问题的答案。你如何从Node.js执行PowerShell脚本?该脚本与Node.js实例在同一台服务器上。
我在网上和Stackoverflow上寻找答案,但没有找到这个问题的答案。你如何从Node.js执行PowerShell脚本?该脚本与Node.js实例在同一台服务器上。
你可以创建一个子进程"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
})
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;
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();
elevate
的函数,可能是你正在寻找的东西。 - muffel-File
参数调用脚本(并使用-NoProfile
参数以实现可预测性),这也使传递参数更容易:child = spawn("powershell.exe", [ '-noprofile', '-file', "c:\\temp\\helloworld.ps1", "arg1", "arg2"])
。在没有-File
的情况下,会隐含-Command
(在Windows PowerShell中,而不是PowerShell Core)。/cc @Ramyachinna - mklement0