Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run powershell script in node js?

I've seen similar questions here.

One question had an accepted answer of

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

I'm on Ubuntu so I changed it to

        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

I dont get any errors when I run the node package but it doesnt seem to be running the powershell script. Nothing is logged in the console.

The powershell script just runs a web request. When I run the powershell script by itself it runs fine and works as expected. Trying to call the powershell script with node is not giving any errors and not producing any results.

Node 12.21.0

like image 637
JabbaTheHut4874 Avatar asked Aug 15 '26 01:08

JabbaTheHut4874


1 Answers

I tried spawning a powershell script that simply outputs Hello World! using node.js (12) in Ubuntu. Following is the code. It seems to work just fine. Can you share the content of your ps1 file?

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}`);
});
like image 81
dina Avatar answered Aug 17 '26 15:08

dina