代码之家  ›  专栏  ›  技术社区  ›  Maximilian Burszley

` powershell.create()`返回空值

  •  2
  • Maximilian Burszley  · 技术社区  · 7 年前

    添加的引用: PowerShellStandard.Library

    在默认值内重新设置 .net-core 项目:

    // ...
    
    using System.Management.Automation;
    using System.Collections.ObjectModel;
    
    // ...
    
    public static void Main(string[] args)
    {
        Collection<PSObject> output;
        using (PowerShell ps = PowerShell.Create())
        {
            ps.AddScript("$test = Get-Date; $test");
            output = ps.Invoke();
        }
    
    // ...
    

    我试过了,有没有 using 阻止,但最终得到的结果是相同的: Create 方法是 创建 PowerShell 对象,但它也是 不引发异常 .

    这是与 PowerShell .net-standard 图书馆?是否有解决方法或其他方法来解决我的问题?

    附加信息 ,这也发生在 RunspaceFactory CreateRunspace 方法,因为我正在探索一种自己管理运行空间的解决方案。

    3 回复  |  直到 7 年前
        1
  •  2
  •   Sani Huttunen    7 年前

    通过查看PowerShellStandard库的源代码,我注意到以下几行:

    public static System.Management.Automation.PowerShell Create ( System.Management.Automation.Runspaces.InitialSessionState initialSessionState ) { return default(System.Management.Automation.PowerShell); }
    public static System.Management.Automation.PowerShell Create (  ) { return default(System.Management.Automation.PowerShell); }
    public static System.Management.Automation.PowerShell Create ( System.Management.Automation.RunspaceMode runspace ) { return default(System.Management.Automation.PowerShell); }
    

    那些会的 总是 返回 default 密封的PowerShell类,这将 总是 null

    这使得PowerShellStandard Library 5.1不支持PowerShell(完全)。

    同样适用于 RunspaceFactory.CreateRunspace .

        2
  •  2
  •   Patrick Meinecke    7 年前

    PowerShellStandard是一个参考库,用于将加载到该库中的项目 AppDomain 作为PowerShell。在这些场景中,所需的程序集已经加载,因此拉低整个SDK是一种浪费。

    为了托管PowerShell(或从PowerShell会话外部使用PowerShell API),需要引用PowerShell SDK(用于PowerShell核心)或GAC程序集(用于Windows PowerShell)。

    要引用SDK,需要 nuget.config 项目的基本目录中添加PowerShell myget作为源的文件。下面是一个例子

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <packageSources>
        <clear />
        <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
        <add key="dotnet-core" value="https://www.myget.org/F/dotnet-core/api/v3/index.json" />
        <add key="powershell-core" value="https://powershell.myget.org/F/powershell-core/api/v3/index.json" />
      </packageSources>
    </configuration>
    

    并在csproj中添加对sdk的引用

    <ItemGroup>
        <PackageReference Include="Microsoft.PowerShell.SDK" Version="6.0.3" />
    </ItemGroup>
    
        3
  •  0
  •   Roman Kuzmin    7 年前

    这是最近发行的 Microsoft.PowerShell.SDK 6.0.4 .

    它看起来是为PowerShell托管和相关任务而设计的。 至少像代码这样的问题在我的.NET核心应用程序中工作得很好。 此包引用已足够。

    推荐文章