Revisions, revisions.

Well, over the past year the PowershellAPI has seen some great changes. For starters, process.exec has been kicked out and replaced with edge.func, which is discussed in further detail further on.

While the PowershellAPI worked "fine" throughout its deployment, there were still things that bothered me. Multi-line scripts were fidgety, parsing data from Powershell was a fuss, requests took forever(~5+ seconds, no matter the task) and allowing Mac Addresses to work with our network took three to five entire seconds a piece to complete. So, I did some research and came across the Edge.js node module.

Edge.js, why and how?

Let's start with the why. Instead of creating new processes for each command like the PowershellAPI used to with process.exec, Edge.js uses only one instance for any amount of commands. The majority of the time associated with executing commands using process.exec is spent waiting for Powershell to initialize. Five seconds per request is unacceptable and incredibly inefficient. But with Edge.js, request times are dependent upon the command ran only. So, running Get-ADUser takes the PowershellAPI only ~500ms to execute, store the result in a database then send a response to the user.

Now, the how. First things first, you need:
, Then, install Edge.js and the Edge-ps node modules:
npm install edge edge-ps

Why is the second module needed? Edge.js isn't just for Powershell, it includes support for Python, C#, .NET, F# and more. But we don't need all of that power when we're just working with Powershell, so let's only use edge-ps.

Next, in your server.js, you only need to require the edge module:
var edge = require('edge');

The edge module will automatically detect the edge-ps module. Now we can declare a Powershell function, using edge.func:

var helloWorld = edge.func('ps', function() {/* "Hello world, I'm $inputFromJS and today is $(Get-Date)" */};

A few things to point out here: Any code within the function in the new edge.func needs to be wrapped inside multi-line (/**/) syntax. Otherwise, edge will complain and throw errors your way. Currently, edge can only use one parameter specified by the user, and that parameter is represented by $inputFromJS. And to get text output (like console.log) you have to wrap the line of Powershell with quotes "".

Let's move on to working with that function. To call it, simply use:
helloWorld('Kyle', function(error, result) { if (error) throw error; console.log(result[0]); });

The output will be:
Hello world, I'm Kyle and today is Wednesday, February 3, 2016 2:56:25 PM

Hooray, we've dipped our feet into executing Powershell within the node.js environment. Stick around for future posts, 'cause I'll be going into detail with handling scripts made by users, parsing Powershell output as JSON, and much more!