Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute windows powershell command using childprocess and nodejs?

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?

like image 678
machinebit Avatar asked Mar 12 '23 18:03

machinebit


1 Answers

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.

like image 73
Ran Cohen Avatar answered Apr 26 '23 16:04

Ran Cohen