You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js中调用带参数的PowerShell脚本

Node.js调用带参数PowerShell脚本报错解决

问题场景

尝试用Node.js调用带参数的PowerShell脚本,原代码如下:

var spawn = require("child_process").spawn;

let comd = '"C:\\Cmdlets\\StartSessionPasswordShown.ps1 "arg1" "arg2" 35107 "arg4"';
child = spawn("powershell.exe", [comd]);
child.stdout.on("data", function (data) {
    let res = data;
    console.log("Powershell Data: " + res);
});
child.stderr.on("data", function (data) {
    console.log("Powershell Errors: " + data);
});
child.on("exit", function () {
    console.log("Powershell Script finished");
});
child.stdin.end();

运行后出现以下错误:

表达式或语句中出现意外标记“arg1”。
字符串缺少终止符: "。

Powershell 错误信息:
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken

错误原因

错误出在参数传递方式:将整个命令拼接成单个字符串传给spawn,导致PowerShell解析时出现引号嵌套的语法错误。spawn要求第二个参数是独立参数组成的数组,而非完整命令字符串。

解决代码

修正后的正确代码如下:

const spawn = require("child_process").spawn;

// 拆分脚本路径与参数
const scriptPath = "C:\\Cmdlets\\StartSessionPasswordShown.ps1";
const scriptArgs = ["arg1", "arg2", 35107, "arg4"];

// 按PowerShell要求传递参数:-File 指定脚本,后续为脚本参数
const child = spawn("powershell.exe", ["-File", scriptPath, ...scriptArgs]);

child.stdout.on("data", (data) => {
    console.log("Powershell 输出: " + data.toString());
});

child.stderr.on("data", (data) => {
    console.log("Powershell 错误: " + data.toString());
});

child.on("exit", () => {
    console.log("Powershell 脚本执行完成");
});

child.stdin.end();

关键说明

  • 使用-File参数明确告知PowerShell执行指定路径的脚本,这是调用本地脚本的标准方式
  • spawn的第二个参数数组中,每个元素对应一个独立的命令行参数,PowerShell会自动正确解析,避免引号嵌套问题
  • 将data转为字符串输出,避免Buffer直接拼接导致的乱码或格式问题
  • 用const声明无需重新赋值的变量,符合现代JS编码规范

内容的提问来源于stack exchange,提问作者Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 14:48:15