我目前正在将库从.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 中调用运行空间(或执行一些合适的解决方法(会使用什么?
Runspace 只是 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);