How to execute windows powershell command using childprocess and nodejs?

18,029

Solution 1

You can use Node-PowerShell.

Node-PowerShell taking advantage of two of the simplest, effective and easy tools that exist in the today technology world. On the one hand, NodeJS which made a revolution in the world of javascript, and on the other hand, PowerShell which recently came out with an initial open-source, cross-platform version, and by connecting them together, gives you the power to create any solution you were asked to, no matter if you are a programmer, an IT or a DevOps guy.

Solution 2

I believe you shold pass the code with -command before it. Default PowerShell syntax is: powershell.exe -command "get-wmiobject ...".

Something like this:

exec("powershell.exe",["-command \"Get-WmiObject -Class win32_diskdrive | Where { $_.InterfaceType -eq 'USB' }\""], function (err, stdout, stderr) {
    console.log(err);
    console.log(stdout);
    console.log(stderr);
});

Solution 3

Another way...

exec('command here', {'shell':'powershell.exe'}, (error, stdout, stderr)=> {
  // do whatever with stdout
})
Share:
18,029
machinebit
Author by

machinebit

Updated on June 08, 2022

Comments

  • machinebit
    machinebit almost 2 years

    I am trying to run a powershell command through a nodejs script. I have found the following two articles which have shown me something similar to what I am trying to acheive: Execute Windows Commands with Nodejs Execute powershell script from nodejs

    On a button click event, I am trying to list the usb devices currently attached to the system along with its Drive Letter (C, D, E etc). If I run the command in the powershell on its own, it works (I am unable to get it to display the drive letter though). However, if I run it as part of my script it does not work. Below is my code:

    if (process.platform === 'win32' || process.platform === 'win64') {
        exec("powershell.exe",["GET-WMIOBJECT win32_diskdrive | Where { $_.InterfaceType –eq 'USB' }"], function (err, stdout, stderr) {
            console.log(err);
            console.log(stdout);
            console.log(stderr);
        });
    }
    

    What am I doing wrong?