问题描述
我正在尝试实现一个需要运行PowerShell脚本的.NetCore 3.1控制台应用程序。但是,当我尝试运行它时,出现以下错误-
Cannot perform operation because the runspace is not in the 'Opened' state. Current state of runspace is 'broken'.
运行PS脚本的代码如下:
using System.Management.Automation;
public async Task<string> RunScript(string scriptToRun)
{
// create a new hosted PowerShell instance using the default runspace.
using PowerShell ps = PowerShell.Create();
// specify the script code to run.
ps.AddScript(scriptToRun);
// execute the script and await the result.
var pipelineObjects = await ps.InvokeAsync().ConfigureAwait(false);
// print the resulting pipeline objects to the console.
var output = new StringBuilder();
foreach (var item in pipelineObjects)
{
output.Append(item.BaSEObject.ToString());
}
return output.ToString();
}
任何想法可能是什么问题?
解决方法
通过创建自定义运行空间来解决此问题。 请参阅本文-How to run powershell core scripts from net core applications