在Node.js中运行PowerShell脚本?

7

我在这里看到了类似的问题。

其中一个问题有一个被接受的答案是

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脚本只是运行一个Web请求。当我单独运行powershell脚本时,它能正常运行并按预期工作。尝试使用node调用powershell脚本不会产生任何错误,并且也没有产生任何结果。

Node版本为12.21.0


1
PowerShell在Ubuntu上?为什么? - Marc
1
我不懂bash,而且在从Windows转移到Ubuntu之前,我已经在Windows上编写了这个脚本。 - JabbaTheHut4874
没有错误也没有结果,但是node进程退出了吗?顺便说一句:看起来这里不需要child.stdin.end();,因为你没有以编程方式提供标准输入。 - mklement0
1个回答

1
我尝试使用Ubuntu中的node.js(12)生成一个简单输出Hello World!的powershell脚本。以下是代码。它似乎工作得很好。您可以分享一下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}`);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接