简体   繁体   中英

How to push powershell command result to json response in NodeJs using Express?

How to handle this task?

I need push data from Powershell.on event to response some data to a client web page. But I'm not a good programmer. How to do that?:

router.all('/', (req, res, next) => {
    var NetbiosName = req.query.hostname.split('.', 1);
    var cmd = "New-ADComputer -Name " +  NetbiosName[0] + " -SamAccountName " + 
    NetbiosName[0]; 
    var gdata;
    let ps = new PowerShell(cmd);
    ps.on("error", err => {
      console.error(err);
    });
    ps.on("output", data => {
      //need to push this data to responce json
      console.log(data);
    });
    ps.on("error-output", data => {
      //need to push this data to responce json
      console.error(data);
    });
    ps.on("end", code => {
    });

    //console.log(ps.send(['help',]));
    res.status(200).json({
      "hostname": req.query.hostname,
      "userclass": req.query.userclass,
      "host": NetbiosName[0],
      "cmd": cmd,
      "data": "Data from ps.on",
    });
    //console.log(util.inspect(req));
});
  1. Write a function to send the data back to the client.

     function sendResponse(data) { res.status(200).json({ "hostname": req.query.hostname, "userclass": req.query.userclass, "host": NetbiosName[0], "cmd": cmd, "data": data }); } 
  2. Call that function from your declared events output and error-output

     ps.on("output", data => { sendResponse(data); }); ps.on("error-output", data => { sendResponse(data); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM