【问题标题】:Execute PowerShell script from NodeJS results in "running scripts is disabled on this system"从 NodeJS 执行 PowerShell 脚本会导致“在此系统上禁用正在运行的脚本”
【发布时间】:2022-11-10 00:55:19
【问题描述】:

我正在尝试从节点运行 powershell 脚本。这是我当前的代码:

try {
    var spawn = require("child_process").spawn,child;
    child = spawn("powershell.exe", ['-file', "..\\build.ps1", "-devmode"])
    child.stdout.on("data",function(data){
        //console.log("Powershell Data: " + data);
    });
    child.stderr.on("data",function(data){
        console.log("Powershell Errors: " + data);
    });
    child.on("exit",function(){
        console.log("Powershell Script finished");
    });
    child.stdin.end(); //end input
} catch (error) {
    console.error(error);
}

代码基于this question。当我运行它时,我收到以下错误:

Powershell Errors: File C:\<path>\build.ps1 cannot be loaded because running scripts is disabled on this system. For more information,
see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
    + CategoryInfo          : SecurityError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnauthorizedAccess

我尝试设置执行策略Set-ExecutionPolicy -ExecutionPolicy Undefined -Scope LocalMachine,并且在调用脚本时也尝试绕过它,如下所示:

child = spawn("powershell.exe", ['-ExecutionPolicy ByPass', '-file', "..\\build.ps1", "-devmode"])

这只是导致The term '-ExecutionPolicy' is not recognized as the name of a cmdlet, function, script file, or operable program.

那么如何从节点执行此脚本而不会出现执行策略错误?

【问题讨论】:

    标签: node.js powershell command-line-interface executionpolicy


    【解决方案1】:

    当您使用 Windows 时PowerShell CLI(powershell.exe) 与-File 参数直接调用.ps1脚本文件, 使用-ExecutionPolicy命令行参数确实是覆盖脚本文件execution policy的唯一有效方法 特别指定, 仅针对给定进程:-ExecutionPolicy Bypass 相当于调用
    Set-ExecutionPolicy Bypass -Scope Process -Force 来自 PowerShell 会话内部。

    但是,要通过spawn 调用,每个参数 - 无论它是否代表参数姓名或者价值- 必须通过作为自己的数组元素

    spawn("powershell.exe", ['-ExecutionPolicy', 'ByPass', '-file', "..\build.ps1", "-devmode"])
    

    至于你尝试了什么

    在您的尝试中,spawn 必须在生成的命令行(在 Windows 上)上将 '-ExecutionPolicy Bypass' 包含在 "..." 中,因为它包含空格。

    powershell.exe 解析生成的命令行时,它会不是认出
    "-ExecutionPolicy Bypass" 尝试将 -ExecutionPolicy 参数与值一起传递;事实上,它根本不将此参数识别为 CLI 参数,因此默认将其视为PowerShell 源代码- 即好像它已传递给默认CLI 参数,-Command (-c)。

    也就是说,实际上您的尝试等同于从 PowerShell 会话内部将 -ExecutionPolicy Bypass ... 作为命令提交,这会导致您看到的错误。

    【讨论】:

      【解决方案2】:

      在您的 Windows 设置中,导航到 Privacy &amp; Security > For developers。然后向下滚动到Powershell 下拉菜单。启用“更改执行策略以允许本地 PowerShell 脚本在不签名的情况下运行。需要对远程脚本进行签名”。

      【讨论】:

        【解决方案3】:
        spawn("Powershell.exe",['-ExecutionPolicy', 'ByPass', "file/path/tmp1/test.ps1"]);
        

        【讨论】:

        • 请添加一些解释以帮助未来的读者为什么这个答案可以解决问题。谢谢你。
        猜你喜欢
        • 2019-07-13
        • 2011-05-01
        • 2021-10-27
        • 2021-02-14
        • 2018-06-08
        相关资源
        最近更新 更多