To execute PowerShell script from Node.js, we call the spawn
function.
For instance, we write
const spawn = require("child_process").spawn;
const child = spawn("powershell.exe", ["c:\\temp\\helloworld.ps1"]);
child.stdout.on("data", (data) => {
console.log(data);
});
child.stderr.on("data", (data) => {
console.log(data);
});
child.on("exit", function () {
console.log("Powershell Script finished");
});
child.stdin.end();
to call spawn
to run powershell.exe with the path to the PowerShell script.
We listen for output by calling child.stdout.on
to listen for data
events.
We listen for errors by calling child.stderr.on
to listen for data
events.
And we call child.on
with 'exit'
to listen for process exit.