The*_*le1 7 c# powershell .net-core .net-standard
添加参考: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();
}
// ...
Run Code Online (Sandbox Code Playgroud)
我已经尝试过使用或不使用using块,但最终得到相同的结果:该Create方法没有创建PowerShell对象,但也没有抛出异常。
这是图书馆的常见问题吗PowerShell .net-standard?有解决方法或其他方法来解决我的问题吗?
附加信息,当我自己探索管理运行空间的解决方法时,RunspaceFactory类方法也会发生这种情况。CreateRunspace
PowerShellStandard 是一个参考库,它适用于将加载到与AppDomainPowerShell 相同的项目。在这些情况下,所需的程序集已经加载,因此拉取整个 SDK 会很浪费。
为了托管 PowerShell(或以其他方式从 PowerShell 会话外部使用 PowerShell API),您需要引用 PowerShell SDK(对于 PowerShell Core)或 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>
Run Code Online (Sandbox Code Playgroud)
并在您的csproj中添加对SDK的引用
<ItemGroup>
<PackageReference Include="Microsoft.PowerShell.SDK" Version="7.1.3" />
</ItemGroup>
Run Code Online (Sandbox Code Playgroud)
更新 04/15/2021
您不再需要 nuget 配置,SDK 现在可以在 nuget 上使用。
查看 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); }
Run Code Online (Sandbox Code Playgroud)
这些将始终返回default密封 PowerShell 类的 ,并且始终为null。
这使得 PowerShell 标准库 5.1 不(完全)支持 PowerShell。
同样适用于RunspaceFactory.CreateRunspace.
| 归档时间: |
|
| 查看次数: |
3781 次 |
| 最近记录: |