从NodeJS执行PowerShell脚本会导致“在此系统上禁用运行脚本”

r6vfmomb  于 2022-11-10  发布在  Shell
关注(0)|答案(3)|浏览(288)

我正在尝试从节点运行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.
那么,如何才能在不出现执行策略错误的情况下从节点执行此脚本?

6ss1mwsb

6ss1mwsb1#

当您使用带有**-File参数的WindowsPowerShell CLI(powershell.exe)直接调用.ps1脚本文件时,使用**-ExecutionPolicy CLI参数确实是覆盖脚本文件execution policy的唯一有效方法仅对于给定进程:-ExecutionPolicy Bypass等同于调用
来自PowerShell会话内部的Set-ExecutionPolicy Bypass -Scope Process -Force
但是,要从spawn调用执行此操作,**每个参数--无论它表示的是参数
名称还是值*--都必须作为其自己的数组元素进行传递

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

至于你尝试了什么
在您的尝试中,spawn必然会将'-ExecutionPolicy Bypass'包含在结果命令行(在Windows上)的"..."中,因为其中包含空格。
powershell.exe解析生成的命令行时,它无法识别
"-ExecutionPolicy Bypass"被视为试图传递带有值的-ExecutionPolicy参数;事实上,它根本不将此参数识别为CLI参数,因此默认将其视为PowerShell源代码-即好像它已被传递给默认CLI参数-Command(-c)。
也就是说,您的尝试实际上等同于从PowerShell会话内部将-ExecutionPolicy Bypass ...作为命令提交,这将导致您看到的错误。

yrefmtwq

yrefmtwq2#

spawn("Powershell.exe",['-ExecutionPolicy', 'ByPass', "file/path/tmp1/test.ps1"]);
qv7cva1a

qv7cva1a3#

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

相关问题