首页 > 解决方案 > 在节点 js 中使用回调函数执行 powershell 脚本

问题描述

我编写了一个节点 JS 脚本,它应该使用 PowerShell 命令行执行。然后将 PowerShell 响应返回给 angularjs。PowerShell 命令的执行时间超过 5 分钟。所以节点正在向 angularjs 发送一个空响应。为此,我尝试了回调函数。但我得到了同样空洞的回应。请帮我解决这个问题。

这是在节点 js 中使用回调函数执行 powershell 的代码

let ps = new shell({
        executionPolicy: 'Bypass',
        noProfile: true
    });

function getData(callback){
    ps.addCommand('C:/Users/sowmi096/Desktop/Code/jobid.ps1',a)
    ps.invoke()
    .then(output => {
        return callback(null,output);
    })
    .catch(err => {
        return callback(null,err);
        ps.dispose();
    });
}
getData(function onGetData(err,data){
    if(err)
        res.send(err);
    res.send(data);
});

标签: javascriptnode.jspowershell

解决方案


tl;博士

要让您的 PowerShell 命令完成执行,您必须调用ps.dispose().


看起来您正在使用node-powershellnpm 包并尝试调整其示例代码。

不幸的是,在撰写本文时,此示例代码存在缺陷,因为它ps.dispose()在成功案例中缺少对代码的调用,这意味着 PowerShell 命令永远不会退出。

这是一个工作示例(假设软件包已安装npm install node-powershell):

const shell = require('node-powershell')

let ps = new shell({
  executionPolicy: 'Bypass',
  noProfile: true
});

// You can pack everything into the 1st argument or pass arguments as
// parameter-name-value objects; note the need to use null for [switch] parameters.
ps.addCommand("write-verbose", [ { verbose: null }, { message: 'hello, world'} ])

// IMPORTANT: ps.dispose() MUST be called for execution to finish.
ps.invoke()
  .then(output => {
    console.log(output)
    ps.dispose()  // This was missing from your code.
  })
  .catch(err => {
    console.log(err)
    ps.dispose()
  });

推荐阅读