【问题标题】:Invoking powershell script within c# that calls another powershell script is throwing an UnauthorizedAccessException在调用另一个 powershell 脚本的 c# 中调用 powershell 脚本会引发 UnauthorizedAccessException
【发布时间】:2020-09-11 08:12:18
【问题描述】:

下面的函数很适合我的测试

    private static void RunScript(string scriptText)
    {
        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript(scriptText);
        pipeline.Commands.Add("Out-String");
        Collection<PSObject> results = pipeline.Invoke();
        runspace.Close();
    }

我这样称呼这个函数

RunScript(File.ReadAllText("test.ps1"));

一切都很好。现在我已经修改了 test.ps1 以调用其他 powershell 脚本。

但是现在我运行它时遇到异常。

UnauthorizedAccessException: 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.

我猜我需要将执行策略设置为“绕过”。我该如何设置?

还有没有办法将 powershell 脚本文件名提供给 Pipeline 对象而不是脚本文件的内容?

【问题讨论】:

  • Set-ExecutionPolicy -ExecutionPolicy ByPass
  • 为什么要从 C# 调用 PowerShell 脚本而不是本机函数?
  • 它与运行外部 powershell 脚本以供其他人扩展功能的解决方案有关。
  • 我知道调用 powershell 的命令,但我想知道如何通过 c# powershell API 指定它?

标签: c# powershell runspace


【解决方案1】:

经过实验,发现我可以简单地多次调用我的函数。一次设置策略,下次调用任何脚本。该政策似乎是在一次调用后设置的。

RunScript("Set-ExecutionPolicy -Scope Process -ExecutionPolicy ByPass");
RunScript(File.ReadAllText("test.ps1"));

private static void RunScript(string scriptText)
{
    Runspace runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(scriptText);
    pipeline.Commands.Add("Out-String");
    Collection<PSObject> results = pipeline.Invoke();
    runspace.Close();
}

您还可以对命令进行排队,即

private static void RunScript(string scriptText)
{
    Runspace runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript("Set-ExecutionPolicy -Scope Process -ExecutionPolicy ByPass");
    pipeline.Commands.AddScript(scriptText);
    pipeline.Commands.Add("Out-String");
    Collection<PSObject> results = pipeline.Invoke();
    runspace.Close();
}

【讨论】:

    猜你喜欢
    • 2015-07-07
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多