簡體   English   中英

從 Node.js 執行 Powershell 腳本

[英]Execute Powershell script from Node.js

我一直在瀏覽網絡和 Stackoverflow,但沒有找到這個問題的答案。 您將如何從 Node.js 執行 Powershell 腳本? 該腳本與 Node.js 實例位於同一服務器上。

您可以只生成一個子進程“powershell.exe”並收聽命令輸出的標准輸出和錯誤的標准錯誤:

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
})

除了公認的答案之外,還有一個名為Edge.js的 Node.JS 庫,它允許從 Node 內部執行各種語言。 包括 C#、J#、.Net、SQL、Python、 PowerShell等 CLR 語言。

請注意,Edge.js 需要 PowerShell 3.0 並且僅適用於 Windows(許多其他功能也適用於 Mac 和 Linux)。

或者你可以只使用Node-PowerShell

Node-PowerShell 利用當今技術世界中存在的兩個最簡單、有效和簡單的工具。 一方面,在 JavaScript 領域掀起革命的 NodeJS,另一方面,最近推出了初始開源、跨平台版本的 PowerShell,並將它們連接在一起,使您能夠創建您被要求的任何解決方案,無論您是程序員、IT 人員還是 DevOps 人員。

這個選項對我有用,當腳本不存在時,但你想動態生成一些命令,發送它們,並在節點上處理結果。

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM