Visual Studio 由于执行策略,无法执行 Powershell 脚本

Visual Studio can't execute a Powershell script due to execution policy

我正在尝试 运行 c# 应用程序中的基本 powershell 脚本,但我似乎无法 运行。我已经尝试过这段代码,无论是否在管道创建中添加了执行策略代码,都得到了相同的结果。

static void Main(string[] args)
    {
        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();

        Pipeline pipeline = runspace.CreatePipeline("Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned");


        pipeline.Commands.Add(@"C:\Users\Bob\Desktop\testScript.ps1");

        // Execute PowerShell script
        var results = pipeline.Invoke();
    }

我收到的错误是这样的:

System.Management.Automation.PSSecurityException: '无法加载文件 C:\Users\Bob\Desktop\testScript.ps1,因为 运行ning 脚本在此系统上被禁用。有关详细信息,请参阅 about_Execution_Policies https://go.microsoft.com/fwlink/?LinkID=135170.'

当我运行“get-executionpolicy -list”时,我的执行策略似乎没问题。

  • 通常,持久配置的脚本 execution policy 也适用于基于 PowerShell SDK 的项目,例如您的项目。

  • 而您的 Get-ExecutionPolicy -List output implies that RemoteSigned is the effective policy (as reported when you omit -List), the color of your screenshots suggest that you were asking for Windows PowerShell's policy, which is separate from the execution policy for the cross-platform, install-on demand PowerShell (Core) v6+ 版本。

  • 因此,您无法执行 local 脚本 - RemoteSigned 应该允许 - 可能有两个原因之一:

    • 如果您的项目基于 PowerShell (Core) v6+ 的 SDK(通过 Microsoft.PowerShell.SDK NuGet 包),您将拥有咨询 - 并可能修改 - 有效的执行政策(运行 pwsh -c Get-ExecutionPolicy 查看有效的政策)

      • 如果您实际上没有安装 PowerShell (Core) 6+ 本身(即,如果您只使用其 SDK),请使用底部的解决方案 -无论如何这可能更可取。
    • 正如 Mathias 在评论中指出的那样,另一个可能的原因是您的本地脚本可能已通过网络浏览器从网络下载,在在这种情况下,出于执行策略的目的,它被视为 远程 文件。将其文件路径作为 one-time 操作传递给 Unblock-File 应该可以解决问题。


退一步:

如果您信任要调用的本地脚本,您可以绕过执行策略仅适用于您的应用程序,通过相应地配置您的 PowerShell SDK 会话 - 请参阅 .