2012-04-16 311 views
18

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

回答

43

你可以只生成一個子進程「powershell.exe」,並聽取stdout中,命令輸出和標準錯誤的錯誤:

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 
+0

完美。十分感謝你的幫助。這正是我所期待的。完美無瑕地工作。 – 2012-04-16 22:02:21

+3

我知道這是舊的,但可以與管理權限運行powershell? – Vandervidi 2015-12-03 22:25:37

+0

http://serverfault.com/a/464024/202283 – digitalextremist 2015-12-13 01:43:11

10

除了公認的答案,有一個Node.js的庫調用Edge.js,它允許從Node內執行各種語言。包括C#,J#,.Net,SQL,Python,PowerShell和其他CLR語言。

請注意Edge.js要求PowerShell 3.0 &只適用於Windows(許多其他功能也適用於Mac和Linux)。

6

此選項適用於我,當腳本尚未存在時,但您想要動態生成某些命令,發送它們,並將結果處理回節點。

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; 
2

或者您可以使用Node-PowerShell

Node-PowerShell利用當今技術世界中存在的兩種最簡單,最有效和最簡單的工具。一方面,在JavaScript的世界中進行了革命的NodeJS,另一方面,最近推出了最初的開放源代碼,跨平臺版本的PowerShell,並將它們連接在一起,爲您提供了強大的功能無論您是程序員,IT還是DevOps人員,都可以創建任何您需要的解決方案。

+2

歡迎來到Stack Overflow!一個解決方案的鏈接是受歡迎的,但請確保你的答案是有用的沒有它:[添加鏈接的上下文](/ meta.stackexchange.com/a/8259),以便您的同行用戶將有一些想法是什麼和爲什麼它在那裏,然後引用你鏈接到的頁面中最相關的部分,以防目標頁面不可用。 [僅僅是一個鏈接的答案可能會被刪除。](// stackoverflow.com/help/deleted-answers) – FelixSFD 2017-03-03 16:48:43