programing

Node.js에서 Powershell 스크립트 실행

oldcodes 2023. 10. 21. 10:50
반응형

Node.js에서 Powershell 스크립트 실행

저는 웹과 스택 오버플로우를 둘러보았지만 이 질문에 대한 답을 찾지 못했습니다.Node.js에서 파워셸 스크립트를 어떻게 실행하시겠습니까?스크립트가 Node.js 인스턴스와 동일한 서버에 있습니다.

하위 프로세스 "powershell.exe"를 생성하고 명령 출력에 대해서는 stdout을 듣고 오류에 대해서는 stderr을 들을 수 있습니다.

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

이 작업을 수행하는 새로운 방법

const { exec } = require('child_process');
exec('command here', {'shell':'powershell.exe'}, (error, stdout, stderr)=> {
    // do whatever with stdout
})

스크립트가 아직 존재하지 않지만 동적으로 명령을 생성하여 전송하고 결과를 노드에서 다시 작업하고자 할 때 이 옵션을 사용할 수 있습니다.

var PSRunner = {
    send: function(commands) {
        var self = this;
        var results = [];
        var spawn = require("child_process").spawn;
        var child = spawn("powershell.exe", ["-Command", "-"]);

        child.stdout.on("data", function(data) {
            self.out.push(data.toString());
        });
        child.stderr.on("data", function(data) {
            self.err.push(data.toString());
        });

        commands.forEach(function(cmd){
            self.out = [];
            self.err = [];
            child.stdin.write(cmd+ '\n');
            results.push({command: cmd, output: self.out, errors: self.err});
        });
        child.stdin.end();
        return results;
    },
};

module.exports = PSRunner;

언급URL : https://stackoverflow.com/questions/10179114/execute-powershell-script-from-node-js

반응형