Search code examples
javascriptpowershellwakanda

How to use SystemWorker to execute PowerShell commands?


I'm trying to achieve something with the SystemWorker of the Wakanda server-side API. But I cannot achieve it. I'm sure I am missing something on the workflow of SystemWorker.

I want to launch the PowerShell from Windows and then run two commands inside. To do that manually, I just run powershell in the cmd.exe and then I can start to write PowerShell commands and get back my data.

In Wakanda I have set up an ssjs file with that code:

var powershell = new SystemWorker(['powershell'],null);

powershell.postMessage('Add-Type -AssemblyName "PresentationCore"');
powershell.endOfInput();
powershell.postMessage('[Windows.Media.Fonts]::SystemFontFamilies');
powershell.endOfInput();

powershell.onmessage = function (event) {
    var data = event.data;
    debugger;
};
powershell.onerror = function (event) {
    debugger;
};
powershell.onterminated = function (event) {
    // potentially check event.exitStatus or event.forced
    debugger;
    exitWait();
};
wait();

I have also a systemWorkers.json file containing this:

[
    {
        "name" : "powershell",
        "executable" :
        [
            { "path" : "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" }
        ]
    }
]

I just want to execute the two commands Add-Type -AssemblyName "PresentationCore" and [Windows.Media.Fonts]::SystemFontFamilies in my PowerShell to get the list of all the fonts available on the machine.

If I look into the task manager, the PowerShell is launched, but I never achieve to execute my two command lines or get back the data. I only achieve to end up in the onterminated callback.

What I am missing?


Solution

  • Finally I reach to make it work.

    Now I put my command in a ps1 file that I give as an argument to my SystemWorker

    So it look like this :

    var powershell = new SystemWorker(['powershell "C:/Users/<MyName>/Desktop/<myScript>.ps1"'],null);
    
    powershell.onmessage = function (event) {
    
    };
    powershell.onerror = function (event) {
    };
    powershell.onterminated = function (event) {
        exitWait();
    };
    wait();
    

    I think is more easy to do this way so all my commands are in one file and then I just ask the System worker to execute the PowerShell and to run my script.