javascript - 在 Node js 中运行 powershell 脚本?

标签 javascript node.js powershell

我在这里看到过类似的问题。
一个问题的公认答案是

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/

相关文章:

javascript - 每次按键时数组都会重置

javascript - Promise 未使用 async 和 wait 解决

python - 无法通过 pip 或 npm 安装软件包

javascript - 如何使用私有(private) GitHub 存储库作为 yarn 依赖项(未安装内部 deps)?

Javascript/Node - 将数据库中存储为文本的 json 转换为 JSON 对象

javascript - 在 Google Apps 脚本 (JavaScript) 中获取特定字符串格式的第二天日期

Azure函数: is it possible to give multiple parameters to a queue trigger?

powershell - Powershell参数依赖于另一个参数

windows - 我无法使用wsl,无效的命令行选项: --install下载linux

javascript - 如何检查 window.open() 打开同一页面两次