添加引用: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
block ,我都试过了,但我最终得到了相同的结果:Create
方法不是创建一个 PowerShell
对象,但它也不会抛出异常。
这是 PowerShell
.net-standard
库的常见问题吗?是否有解决方法或其他方法来解决我的问题?
其他信息,这也发生在 RunspaceFactory
类 CreateRunspace
方法中,因为我正在探索自己管理运行空间的解决方法。
最佳答案
PowerShellStandard 是一个引用库,它适用于将加载到与 PowerShell 相同的 AppDomain
中的项目。在那些场景中,所需的程序集已经加载,因此拉下整个 SDK 是一种浪费。
为了托管 PowerShell(或以其他方式从 PowerShell session 外部使用 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>
并且在您的csproj中添加对SDK的引用
<ItemGroup>
<PackageReference Include="Microsoft.PowerShell.SDK" Version="7.1.3" />
</ItemGroup>
2021 年 4 月 15 日更新
您不再需要 nuget 配置,SDK 现在可以在 nuget 上使用。
关于c# - `PowerShell.Create()` 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51733481/