我在这里看到过类似的问题。
一个问题的公认答案是
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
我在Ubuntu上,所以我将其更改为 var spawn = require("child_process").spawn,child;
child = spawn("/usr/bin/pwsh",["/srv/webroot/pauseRS.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
运行 Node 包时我没有收到任何错误,但它似乎没有运行 powershell 脚本。控制台中没有记录任何内容。powershell 脚本只是运行一个网络请求。当我自己运行 powershell 脚本时,它运行良好并按预期工作。尝试使用 node 调用 powershell 脚本不会给出任何错误并且不会产生任何结果。
Node 12.21.0
最佳答案
我尝试生成一个仅输出 Hello World!
的 powershell 脚本在 Ubuntu 中使用 node.js (12)。以下是代码。它似乎工作得很好。你能分享你的ps1文件的内容吗?
const { spawn } = require('child_process');
const ls = spawn('/usr/bin/pwsh', ['hello.ps1']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
关于javascript - 在 Node js 中运行 powershell 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70406525/