【问题标题】:Is there a .NET Core alternative to System.Management.Automation.RunspaceInvoke?System.Management.Automation.RunspaceInvoke 是否有 .NET Core 替代方案?
【发布时间】:2020-10-07 15:50:35
【问题描述】:

我目前正在将一个库从 .NET Framework 移植到 .NET Core。该库的框架版本利用了 Powershell 中的一些运行空间,我不太熟悉这些运行空间(为了这个问题,暂且不提在 Core 中使用 Powershell 的优点)。相关代码如下

using System.Management.Automation;
using System.Management.Automation.Runspaces;
...
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

            using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
            {
                runspace.Open();
                using (RunspaceInvoke invoker = new RunspaceInvoke(runspace))
                {
                    output = invoker.Invoke("Set-ExecutionPolicy Unrestricted");
                    PrintOutput(output);
...

我知道在 .NET Core 中,已弃用 RunspaceConfiguration 以支持使用 InitialSessionState。但我不确定如何处理 RunspaceInvoke,它在 .NET Core 中不存在(据我所知)。在 .NET Core 中调用运行空间(或执行一些合适的解决方法)会使用什么?

【问题讨论】:

  • 在我看来它是受支持的,因为它是System.Management.Automation NameSpace/Assembly 的一部分? dotnet add package System.Management.Automation --version 7.0.2 docs.microsoft.com/en-us/dotnet/api/… 我对.net-core 了解不多,所以如果我完全不正确,请道歉,但按照文档看起来应该支持RunspaceInvoke
  • System.Management.Automation 在 .NET Core 中受支持。但是,RunspaceInvoke 需要安装 Microsoft.PowerShell.5.ReferenceAssemblies,它只能在 .NET Framework 上运行。在 Visual Studio 中,安装它会给出“此包可能与您的项目不完全兼容”警告
  • 好的,谢谢 Jacob,等我回家后我会仔细研究一下,看看是否有替代 Microsoft.PowerShell.5.ReferenceAssemblies 的方法。您是否尝试使用包加载您的项目,即使它给出了编译警告并且它没有工作?

标签: c# powershell .net-core automation runspace


【解决方案1】:

运行空间只是 Powershell 的一个实例。

要在 .NET Core 中创建 PowerShell 实例,请使用 System.Management.Automation 的 PowerShell 类及其 PowerShell.Create() 方法:

            InitialSessionState runspaceConfiguration = InitialSessionState.Create();

            using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
            {
                runspace.Open();
                using (PowerShell invoker = PowerShell.Create(runspace))
                {

                    output = invoker.Invoke("Set-ExecutionPolicy Unrestricted");
                    PrintOutput(output);

【讨论】:

  • PowerShell.Create() 方法的 documentation 暗示了上述身份(运行空间 = PowerShell 实例),但并不明确。在采用 InitialSessionState 参数的方法版本下,它声明: ============== "Parameters InitialSessionState 用于创建 运行空间 返回 PowerShell PowerShell 的一个实例。=================
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-05
相关资源
最近更新 更多